在大多数情况下,我的 HTTP 请求都没有问题。但是,它们偶尔会挂起。
我使用的代码设置为如果请求成功(响应代码为 200 或 201),则调用 screen.requestSucceeded()。如果请求失败,则调用 screen.requestFailed()。
然而,当请求挂起时,它会在调用上述方法之一之前挂起。我的代码有问题吗?我是否应该使用某种最佳实践来防止挂起?
以下是我的代码。我将不胜感激任何帮助。谢谢!
HttpConnection connection = (HttpConnection) Connector.open(url
+ connectionParameters);
connection.setRequestMethod(method);
connection.setRequestProperty("WWW-Authenticate",
"OAuth realm=api.netflix.com");
if (method.equals("POST") && postData != null) {
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", Integer
.toString(postData.length));
OutputStream requestOutput = connection.openOutputStream();
requestOutput.write(postData);
requestOutput.close();
}
int responseCode = connection.getResponseCode();
System.out.println("RESPONSE CODE: " + responseCode);
if (connection instanceof HttpsConnection) {
HttpsConnection secureConnection = (HttpsConnection) connection;
String issuer = secureConnection.getSecurityInfo()
.getServerCertificate().getIssuer();
UiApplication.getUiApplication().invokeLater(
new DialogRunner(
"Secure Connection! Certificate issued by: "
+ issuer));
}
if (responseCode != 200 && responseCode != 201) {
screen.requestFailed("Unexpected response code: "
+ responseCode);
connection.close();
return;
}
String contentType = connection.getHeaderField("Content-type");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream responseData = connection.openInputStream();
byte[] buffer = new byte[20000];
int bytesRead = 0;
while ((bytesRead = responseData.read(buffer)) > 0) {
baos.write(buffer, 0, bytesRead);
}
baos.close();
connection.close();
screen.requestSucceeded(baos.toByteArray(), contentType);
} catch (IOException ex) {
screen.requestFailed(ex.toString());
}
最佳答案
没有任何痕迹,我只是在黑暗中拍摄。
尝试添加这 2 个调用,
System.setProperty("http.keepAlive", "false");
connection.setRequestProperty("Connection", "close");
保持 Activity 状态是连接失效的常见原因。这些调用将禁用它。
关于Java HTTP 请求偶尔挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2733735/