getHttpResponseCode()在android 2.2中返回-1

前端之家收集整理的这篇文章主要介绍了getHttpResponseCode()在android 2.2中返回-1前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的 Android应用程序中,我试图通过执行POST请求从服务器提取数据.

我正在使用HttpURLConnection类来发出请求,因为Apache的HttpClient不再由android维护.

这就是我正在做的事情.

private boolean callWS() {
    try {

        // To avoid the bug in httpurlconnection prior froyo which
        // causes the getInputStream to return headers along with response
        if (Build.VERSION.SDK_INT < 8)
            System.setProperty("http.keepAlive","false");

        mHttpResponseCode = 0;
        mErrorMessage = "";

        // Initialize connection
        URL connectURL = new URL(mServerUrl);

        HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);
        conn.setReadTimeout(30000); 
        conn.setConnectTimeout(15000); 
        conn.setRequestMethod("POST");

        // Set some headers
        connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        connection.setRequestProperty("Accept-Encoding","deflate,gzip");
        connection.setRequestProperty("Content-Length",mParameters.length() + "");

        // Connect to host
        conn.connect();

        // Write parameters to connection
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(mParameters);
        writer.flush();
        writer.close();

        // Wait for http response code
        mHttpResponseCode = conn.getResponseCode();

        // Read response from connection
        BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int read = 0;
        int bufSize = 1024;
        byte[] buffer = new byte[bufSize];

        while (true) {
            read = bis.read(buffer);
            if (read == -1)
                break;
            baf.append(buffer,read);
        }

        // Decompress gzipped response
        if (conn.getHeaderField("Content-Encoding") != null && conn.getHeaderField("Content-Encoding").contains("gzip"))
            mResponseString = decompress(baf.toByteArray());
        else
            mResponseString = new String(baf.toByteArray());

        mResponse.setResponse(mResponseString);         
        isWSCallSuccessfull = true;
    } catch(UnknownHostException unknownHostException) {
        isWSCallSuccessfull = false;
        mErrorMessage = "Unknown host exception";
        unknownHostException.printStackTrace();
        mLogger.putStacktrace(unknownHostException);
    } catch(SocketException socketException) {
        isWSCallSuccessfull = false;
        mErrorMessage = "Socket Exception";
        socketException.printStackTrace();
        mLogger.putStacktrace(socketException);
    } catch(SocketTimeoutException socketTimeOutException) {
        isWSCallSuccessfull = false;
        mErrorMessage = "Socket Timeout Exception";
        socketTimeOutException.printStackTrace();
        mLogger.putStacktrace(socketTimeOutException);
    } catch(SSLException sslException) {
        isWSCallSuccessfull = false;
        mErrorMessage = "SSL Exception";
        sslException.printStackTrace();
        mLogger.putStacktrace(sslException);
    } catch(IOException ioException) {
        isWSCallSuccessfull = false;
        mErrorMessage = "IO Exception " + ioException.getMessage();
        ioException.printStackTrace();
        mLogger.putStacktrace(ioException);
    }

    mResponse.setHttpResponseCode(mHttpResponseCode);
    mResponse.setErrorMessage(mErrorMessage);
    mResponse.isWSCallSuccessful(isWSCallSuccessfull);

    return isWSCallSuccessfull;
}

除了运行2.2的设备(没有在2.1上试用),这在每个设备上都能正常工作.

在2.2中,它工作正常.但是如果我将这部分代码空闲超过30秒,它会在下一次返回-1作为http响应代码.

另一件需要注意的事情是,这只发生在HTTPS网址,而不是HTTP网址.我不想使用HttpsURLConnection类,因为有时我可能也想使用http.

我没有关闭连接只是为了保持连接活着.我究竟做错了什么?

解决方法

如果你想同时使用Https和Http并且不想创建一个单独的连接 – 如果HttpsUrlConnection解决了你的“-1问题”,你可以使用以下方法
URLConnection conn = new URL(url).openConnection();
if (conn instanceof HttpsURLConnection) {
  // do stuff with cast to HttpsUrlConection
}
else {
  // do stuff with cast to HttpUrlConnection
}

我把this的答案作为参考

原文链接:https://www.f2er.com/android/314893.html

猜你在找的Android相关文章