Android HttpUrlConnection响应等待时间

时间:2012-01-31 20:27:08

标签: java android http httpurlconnection

我有以下代码。我收到HTTP响应代码-1。只是为了排除故障,我想知道在检查http响应代码之前是否应该等待一段时间后再等。

String requestURL = "https://www.google.com";

HttpURLConnection connection = new HttpURLConnection;
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setConnectTimeout(20000);
connection.setReadTimeout(20000);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();

OutputStreamWriter writer = new OutputStreamWriter(this.connection.getOutputStream());
       writer.write(getHttpData());
writer.flush();
writer.close();

if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
    BufferedReader reader = new BufferedReader(new  inputStreamReader(connection.getInputStream()));
}

getResponseCode()或getInputStream()是否阻止调用?我太快读了回应吗?我应该等一下吗?

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

您可能获得奇怪的HTTP响应代码-1的一个原因是与Android平台版本中的-http-keep-alives bug 的连接池(包括)Froyo,即Android v2.2。

Android Developer Blog提供了以下代码段来解决问题(请注意,他们说它不包含Froyo,虽然我们发现它确实如此 - 下面的代码段会相应地修改):

private void disableConnectionReuseIfNecessary() {
    // HTTP connection reuse which was buggy pre-froyo
    if (Integer.parseInt(Build.VERSION.SDK) <= Build.VERSION_CODES.FROYO) {
        System.setProperty("http.keepAlive", "false");
    }
}

尝试在应用启动时调用它,看看它是否解决了您的问题。