2015-01-07 3 views
0

웹 서비스에 액세스하기 위해 Apachage HttpComponent를 사용하여 이상한 동작이 발생했습니다.HttpGet 401 상태 코드 뒤에 200 상태 코드

서버 로그에 액세스 할 수 있으며 서버에 연결하여 httpGet 명령을 실행할 때 처음에는 로그에서 401 상태 (http Unauthorized)와 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). 

이 내용은 내가 안드로이드 응용 프로그램이 코드를 사용하고 있습니다 : 여기

내가 현재 사용하고있는 다음 코드입니다.

+0

가능한 [Apache HttpClient 4의 기본 인증] (http://stackoverflow.com/questions/2014700/preemptive-basic-authentication-with-apache-httpclient-4) –

답변

1

이것은 HTTP 클라이언트의 일반적인 동작입니다. 첫 번째 요청은 인증없이 전송됩니다. 서버가 401을 리턴하면 필요한 신임으로 다시 시도하십시오. 대부분의 경우 웹 브라우저는 사용자와 암호를 묻습니다. 이미 코드에 자격 증명을 제공 했으므로 다시 시도 할 수 있습니다.

받은 결과는 자격 증명을 사용한 요청 이후의 응답입니다.

+0

답변 해 주셔서 감사합니다. 첫 번째 요청에 실존민의 사용을 강요하는 방법이 있습니까? – Joze

+1

확실하지 않습니다. '선매 (preemptive) 인증'을 시도해보십시오. –

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

감사 토마스 Stets

는 드디어 다음 줄을했다.