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.
source share