Getting http 407 error as an IOException

巧了我就是萌 提交于 2019-12-22 09:14:01

问题


I'm using in my android application the HttpURLConnection through a proxy where an authentication is needed. Here is my code and I will explain you after my problem.

HttpURLConnection connection = null;
int responseCode = -1;
try {
    connection = (HttpURLConnection) myUrl.openConnection();
    connection.setInstanceFollowRedirects(false);
    connection.setConnectTimeout(DEFAULT_TIMEOUT);
    connection.setReadTimeout(DEFAULT_TIMEOUT);

    responseCode = connection.getResponseCode();
    System.out.println("ResponseCode = " + responseCode);
} catch (IOException e) {
    System.out.println("Exception : " + e.getMessage());
}

My problem is that I get an exception on the getResponseCode() method which has the following message : Failed to authenticate with proxy. Usually, this specific error has an http error code : 407. But here I just got an exception but not a response code with the 407 value.

I have the solution to apply the login and password to connect to the proxy, but I want to apply this solution only in the case there is a 407 error (and not each time I catch an exception).

Any idea will be appreciated. Thanks.


回答1:


Try catching HttpResponseException instead, and checking its status code (.getStatusCode()) to see if it's 407 (or better yet, HttpURLConnection.HTTP_PROXY_AUTH, more readable).

HttpResponseException is a subclass of IOException, and I think that's the actual exception that's being thrown.

(http://developer.android.com/reference/org/apache/http/client/HttpResponseException.html for more info.)



来源:https://stackoverflow.com/questions/18900143/getting-http-407-error-as-an-ioexception

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