安卓Https状态码-1

3
我正在通过HttpsUrlConnectionHttpUrlConnection(根据设置)从我的Android应用程序连接到Web服务器。到目前为止,我没有遇到任何问题,但是昨天开始我收到了http/https status响应-1。即使存在某种错误,Web服务器也不会返回这样的响应。我连接的服务器在出现问题时会返回errorCodeerrorString。这是我正在使用的代码,但我认为问题不在这里。
    public void UseHttpConnection(String url, String charset, String query) {
    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url)
                .openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Charset", charset);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded;charset=" + charset);
        OutputStream output = null;
        try {
            output = connection.getOutputStream();
            output.write(query.getBytes(charset));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (output != null)
                try {
                    output.close();
                } catch (IOException logOrIgnore) {
                }
        }

        int status = ((HttpURLConnection) connection).getResponseCode();
        Log.i("", "Status : " + status);

        for (Entry<String, List<String>> header : connection
                .getHeaderFields().entrySet()) {
            Log.i("Headers",
                    "Headers : " + header.getKey() + "="
                            + header.getValue());
        }

        InputStream response = new BufferedInputStream(
                connection.getInputStream());

        int bytesRead = -1;
        byte[] buffer = new byte[30 * 1024];
        while ((bytesRead = response.read(buffer)) > 0) {
            byte[] buffer2 = new byte[bytesRead];
            System.arraycopy(buffer, 0, buffer2, 0, bytesRead);
            handleDataFromSync(buffer2);
        }
        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

所以我的问题是,-1 应该代表什么。它是响应某种错误还是其他的什么?
1个回答

5

HTTP响应码-1表示连接或响应处理出现了问题。HttpURLConnection经常在保持连接方面存在错误。

如果你想关闭它,你需要将http.keepAlive系统属性设置为false。

以编程方式实现这一点的方法是在你的应用程序开头放置以下内容:

System.setProperty("http.keepAlive", "false");

是的,这对我也起作用了。我只将它设置为android<2.2,根据谷歌在这里的建议:http://android-developers.blogspot.dk/2011/09/androids-http-clients.html,但似乎这个错误在2.2中也没有被修复,所以将其更改为android<2.3对我有用。 - Jacob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接