HttpGet 401 status code followed by 200 status cod

2020-05-07 19:04发布

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

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

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

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

2条回答
祖国的老花朵
2楼-- · 2020-05-07 19:34

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.

查看更多
我想做一个坏孩纸
3楼-- · 2020-05-07 19:42

To solve my problem, I used an answer (Adam Batkin) from another question related to my problem : Preemptive Basic authentication with Apache HttpClient 4 (Thanks Bret Okken for the link).

I finally had the following line :

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

To get a code like this :

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

Thanks Thomas Stets for the interesting answer.

查看更多
登录 后发表回答