HttpGet 401状态代码后跟200状态代码

时间:2015-01-07 11:34:50

标签: java android http get

我正面临一种使用Apachage HttpComponent访问网络服务的奇怪行为。

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

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

所以我正在搜索如何避免这种行为。有什么想法吗?

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

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应用程序。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

为了解决我的问题,我在另一个与我的问题相关的问题中使用了答案(Adam Batkin):Preemptive Basic authentication with Apache HttpClient 4(感谢Bret Okken的链接)。

我终于得到了以下一行:

httpGet.addHeader(BasicScheme.authenticate(creds, "UTF8", false));

要获得这样的代码:

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);

httpGet.addHeader(BasicScheme.authenticate(creds, "UTF8", false));

HttpResponse response = httpClient.execute(httpGet);
int status = response.getStatusLine().getStatusCode();
Log.v(this, "Response code status: " + status);

感谢Thomas Stets的有趣回答。