HttpGet 401 状态码后跟 200 状态码 [英] HttpGet 401 status code followed by 200 status code

查看:45
本文介绍了HttpGet 401 状态码后跟 200 状态码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Apache HttpComponent 访问网络服务时遇到了奇怪的行为.

I am facing a strange behaviour using the Apachage HttpComponent to access a webservice.

我可以访问服务器日志,当我尝试连接到服务器并执行 httpGet 命令时,我首先可以在日志中看到 401 状态(http 未授权),然后是 200(http 正常).

I have access to the server log and when I am trying to connect to the server and execute the httpGet command I can see in the log at first a 401 status (http Unauthorized) and then a 200 (http OK).

2 次尝试发生在httpClient.execute(httpGet)"期间

The 2 attempts take place during the "httpClient.execute(httpGet)"

所以我正在寻找如何避免这种行为.有什么想法吗?

So I am searching how to avoid this behaviour. Any ideas ?

这是我目前使用的以下代码:

Here is the following code I am currently using :

HttpGet httpGet = new HttpGet(this.url + request);

HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,3000);
HttpConnectionParams.setSoTimeout(httpParameters,5000);

DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
Credentials creds = new UsernamePasswordCredentials(login, password);
httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);

HttpResponse response = httpClient.execute(httpGet);
int status = response.getStatusLine().getStatusCode();
Log.v(this, "Response code status: " + status); // code status = 200 (even if a 401 and then a 200 are visible in the server log).

有关信息,我将此代码用于 Android 应用程序.

For information, I am using this code for an Android application.

推荐答案

这是 HTTP 客户端的常规行为:第一个请求未经身份验证发送.如果服务器返回 401,请使用所需的凭据重试.大多数情况下,Web 浏览器会提示您输入用户名和密码.由于您已经在代码中提供了凭据,因此可以继续重试.

That is the regular behaviour for a HTTP client: The first request is sent without authentication. If the server returns 401, try again with the required credentials. A web browser would in most cases prompt you for user and password. Since you already provided the credentials in your code it can go ahead and try again.

您收到的结果是带有凭据的请求后的响应.

The result you receive is the response after the request with credentials.

这篇关于HttpGet 401 状态码后跟 200 状态码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆