微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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的答案作为参考

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐