HttpURLConnection.getInputStream() 抛出 SocketTimeoutException。

6

我正在使用HttpURLConnection上传图片并获取其响应。
在模拟器和小米设备上工作正常。
但是,在我的索尼设备上,它总是在connection.getInputStream()这一行中遇到SocketTimeoutException异常。
我已经尝试将超时设置为1分钟,但仍然无效。

 public String uploadFile(File file, String requestURL) {

        if (file != null) {
            long fileSize = file.length();
            HttpURLConnection.setFollowRedirects(false);
            HttpURLConnection connection = null;
            try {
                //config of connection
                connection = (HttpURLConnection) new URL(requestURL).openConnection();
                connection.setConnectTimeout(10000);
                connection.setReadTimeout(10000);
                connection.setRequestMethod("PUT");
                connection.setRequestProperty("Content-Type", "image/jpeg");
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-length", "" + fileSize);
                connection.connect();

                //upload file
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                int bytesRead;
                byte buf[] = new byte[1024];
                BufferedInputStream bufInput = new BufferedInputStream(new FileInputStream(file));
                while ((bytesRead = bufInput.read(buf)) != -1) {
                    out.write(buf, 0, bytesRead);
                    out.flush();
                }
                out.flush();
                out.close();

                //get response message, but SocketTimeoutException occurs here
                BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
                StringBuilder sb = new StringBuilder();
                String output;
                while ((output = br.readLine()) != null) {
                    sb.append(output);
                }

                //return response message
                return output;

            } catch (Exception e) {
                // Exception
                e.printStackTrace();
            } finally {
                if (connection != null) connection.disconnect();
            }
        }

        return null;
    }

这个问题是什么原因导致的?如何解决?

附加信息: 我在同一Wi-Fi连接下的设备上进行了测试,并且网络和文件服务器工作正常。测试图像的文件大小约为100〜200 KB。


SocketTimeoutException 是立即发生还是在配置的超时时间之后发生的? - Robert
@Robert 超时后发生了异常。 - Season
不要在循环内部执行 flush。 - user207421
2个回答

0

因为您设置了十秒的读取超时时间,但在十秒内未收到响应。

这是一个恶作剧问题吗?

NB 您不需要设置内容长度头。Java会为您完成。


1
我知道异常是由于长时间读取造成的。但是,为什么我的一个设备不工作,而另一个设备/模拟器却可以工作呢?它们都使用同一个WiFi连接。 - Season
十秒钟并不是一个低值。 - Michele Bontorno
@MicheleBontorno 我不同意。如果你不知道服务器的平均响应时间和方差,你也不可能同意。 - user207421
是的,你说得对。我不知道我在想什么 :) - Michele Bontorno

0

只需删除connection.setReadTimeout()语句,因为默认情况下它会将readTiomeout值设置为0,即它将等待数据直到数据可用。因此,您可能不会收到SocketTimeOut异常。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接