2011-01-29 76 views

回答

0

您需要使用HttpRequestInterceptor類進行身份驗證。

下面是一個例子

HttpRequestInterceptor httpRequestInterceptor = new HttpRequestInterceptor() { 
    public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { 
     AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); 
     CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
       ClientContext.CREDS_PROVIDER); 
     HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); 

     if (authState.getAuthScheme() == null) { 
      AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); 
      Credentials creds = credsProvider.getCredentials(authScope); 
      if (creds != null) { 
       authState.setAuthScheme(new BasicScheme()); 
       authState.setCredentials(creds); 
      } 
     } 
    }  
}; 
+0

這會打開一個新的問題:如何將攔截器添加到AndroidHttpClient中? – lichtzeichenanlage 2011-01-29 12:08:24

+0

你可以讓我知道你爲什麼要使用`AndroidHttpClient`? – 2011-01-29 21:13:32

0

我知道這個問題是舊的,但任何人都磕磕絆絆這個的好處(像我一樣),你可以自己滾動頭與HttpGet對象。像這樣:

httpGet.addHeader("Authorization", "Basic " + Base64.encode(username+":"+password)); 
0

一些增強薩阿德法魯克的答案,下面的代碼對我的作品。

final AndroidHttpClient client = AndroidHttpClient.newInstance("Android"); 

getRequest = new HttpGet(url); 

getRequest.addHeader("Authorization", "Basic " + Base64.encodeToString(new 
       String(username + ":" + password).getBytes(), Base64.NO_WRAP));