Android Https 状态代码-1

And*_*oid 3 android http-status-codes httpurlconnection

HttpsUrlConnection我正在通过或HttpUrlConnection根据设置从我的 Android 应用程序连接到网络服务器。目前我没有遇到任何问题,但昨天我开始收到http/https status回复-1。即使存在某种错误,网络服务器也无法返回给我。我连接的服务器被设计为在出现某种问题时errorCode返回。errorString这是我正在使用的代码,但我认为问题不在这里。

    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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Man*_*anu 5

HTTP 响应代码 -1,表示连接或响应处理出现问题。HttpURLConnection 在保持连接活动状态方面经常出现问题。

如果要关闭,则必须将 http.keepAlive 系统属性设置为 false。

以编程方式执行此操作的方法是将其放在应用程序的开头:

System.setProperty("http.keepAlive", "false");
Run Code Online (Sandbox Code Playgroud)