HttpURLConnection.getInputStream()抛出SocketTimeoutException

Sea*_*son 5 java android urlconnection httpurlconnection socket-timeout-exception

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;
    }
Run Code Online (Sandbox Code Playgroud)

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

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

use*_*421 0

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

这是一个技巧问题吗?

注意:您不需要设置内容长度标头。Java 会为你做这件事。