我正在使用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。