HttpURLConnection responsecode is randomly -1

久未见 提交于 2019-11-27 08:05:16

问题


Hi I'm using following code to establish a url connection. But randomly I get the responseCode -1 (which is the default value of responseCode):

  try {
        URL url = new URL(urlString);

        HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();

        if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            handleData(new DataInputStream(httpconn.getInputStream()), requestCode);
        } else {
            Log.e(TAG, "HttpConnection not OK: " + httpconn.getResponseCode());
            ActivityHelper.httpError(this);
        }
        httpconn.disconnect();
    } catch (Exception e) {
        Log.e(TAG, "handleHttpConnection", e);
        ActivityHelper.httpError(this);
    }

Am I doing something wrong? Because it works perfectly in estimated 9 of 10 attempts.


回答1:


UrlConnection is buggy.

See this blog post from the official Android Developer's blog for a pre-Gingerbread workaround for one problem.

My advice, don't use it. It was still being flaky for me on 3.2. I switched to HttpClient and things have been less bad.



来源:https://stackoverflow.com/questions/8066738/httpurlconnection-responsecode-is-randomly-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!