Android HTTPUrlConnection GetResponseCode进入无限循环

时间:2014-06-09 07:55:46

标签: java android http httpurlconnection

我使用HTTPUrlConnection连接到代理服务器,并使用错误的代理凭据。当我调用getResponseCode时,我希望收到401-身份验证失败。但是,getResponseCode会进入无限循环,并不断向服务器发送(失败)请求。

如果通过浏览器输入了相同的错误凭据,则会弹出一个弹出屏幕以再次请求凭证。

我尝试将keepAlive设置为false,我尝试在Cookie中设置凭据。这些解决方案都没有帮助。

以下是代码:

           connection = (HttpURLConnection) url.openConnection();

           if(connection instanceof HttpsURLConnection){
                ((HttpsURLConnection) connection).setHostnameVerifier(DO_NOT_VERIFY);
            }

              connection.setRequestProperty("Cookie",android.webkit.CookieManager.getInstance().getCookie(sUrl[0]));

                connection.setUseCaches(false);

                connection.setRequestProperty("Cookie", "User name = "+ this.User + "; Password = " + this.Password);


            connection.connect();

            System.setProperty("http.keepAlive", "false");
            int HTTPResponseCode = connection.getResponseCode();

1 个答案:

答案 0 :(得分:0)

设置超时。

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(10000); // set in milliseconds
connection.setReadTimeout(10000); // set in milliseconds