HttpURLConnection.getInputStream () throws a SocketTimeoutException

I am using HttpURLConnection to upload an image and receive its response.
It works on the emulator and my XiaoMi device.
However, it always gets a SocketTimeoutException on my Sony device on the connection.getInputStream() .
I tried to set timeouts to a large value, like 1 minute, but it does not work.

  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; } 

What causes this problem? And how to fix it?

Additional Information: I tested the devices on the same Wi-Fi connection. And the correct network and file server worked correctly. The file size of the scanned images is about 100 ~ 200 kbytes.

+5
source share
2 answers

Since you set the read timeout within ten seconds and no response was received within ten seconds.

Is this a trick?

NB You do not need to set the content length header. Java will do it for you.

0
source

Just delete the connection.setReadTimeout () statement, because by default the readTiomeout value will be set to 0. It will wait for the data until the data is available. In addition, you may not get a SocketTimeOut exception.

0
source

All Articles