6

我正在使用HttpURLConnection上传图像并获得其响应。
它适用于模拟器和我的小米设备。
但是,它总是SocketTimeoutException在我的索尼设备上得到一个就行了connection.getInputStream()
我尝试将超时设置为较大的值,例如 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;
    }

是什么导致这个问题发生?以及如何解决它?

附加信息:我在相同 wifi 连接下的设备上进行了测试。并确保网络和文件服务器正常工作。测试图像的文件大小约为 100~200kbyte。

4

2 回答 2

0

因为你设置了十秒的读取超时,十秒内没有收到响应。

这是一个技巧问题吗?

注意您不需要设置内容长度标头。Java 将为您做到这一点。

于 2015-06-01T10:04:29.820 回答
0

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

于 2017-03-01T04:41:27.567 回答