Java HttpURLConnection.getInputStream()抛出SocketTimeoutException
我正在使用Java HttpURLConnection.getInputStream()抛出SocketTimeoutException,java,android,httpurlconnection,urlconnection,socket-timeout-exception,Java,Android,Httpurlconnection,Urlconnection,Socket Timeout Exception,我正在使用HttpURLConnection上传图像并获取其响应。 它在emulator和我的小米设备上工作。 但是,它总是在我的索尼设备上的connection.getInputStream() 我尝试将超时设置为较大的值,如1分钟,但不工作。 public String uploadFile(File file, String requestURL) { if (file != null) { long fileSize = file.length
HttpURLConnection
上传图像并获取其响应。它在emulator和我的小米设备上工作。
但是,它总是在我的索尼设备上的
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~200KB。因为您将读取超时设置为10秒,并且在10秒内未收到响应 这是个骗人的问题吗
注意:您不需要设置内容长度标题。Java将为您做到这一点。只需删除connection.setReadTimeout()语句,因为默认情况下,它会将readTiomeout值设置为0,即它将等待数据,直到数据可用。因此,您可能无法获得SocketTimeOut异常。SocketTimeoutException是立即发生还是在配置的超时之后发生?@Robert异常发生在timeout之后请勿刷新内部循环。我知道异常发生是由于读取时间过长。但是,为什么我的一个设备不工作,而另一个设备/模拟器工作?他们使用相同的wifi连接。10秒不算低value@MicheleBontorno我不能同意这一点。在不知道服务器的平均响应时间及其变化的情况下,您也不能。是的,您是对的。我不知道我在想什么:)