2012-04-04 328 views
9

我使用Apache HttpComponents訪問Web服務和唐」知道如何在請求中設置用戶名/密碼,這裏是我的代碼:如何設置HTTPGET用戶名/密碼

URI url = new URI(query); 
HttpGet httpget = new HttpGet(url); 

DefaultHttpClient httpclient = new DefaultHttpClient(); 
Credentials defaultcreds = new UsernamePasswordCredentials("test", "test"); 
httpclient.getCredentialsProvider().setCredentials(new AuthScope(HOST, AuthScope.ANY_PORT), defaultcreds); 

HttpResponse response = httpclient.execute(httpget); 

..

但仍得到了401未經授權錯誤。

HTTP/1.1 401 Unauthorized [Server: Apache-Coyote/1.1, Pragma: No-cache, Cache-Control: no-cache, Expires: Wed, 31 Dec 1969 16:00:00 PST, WWW-Authenticate: Basic realm="MemoryRealm", Content-Type: text/html;charset=utf-8, Content-Length: 954, Date: Wed, 04 Apr 2012 02:28:49 GMT] 

我不確定它是否設置用戶/密碼的正確方法?任何人都可以幫忙謝謝。

回答

4

我認爲你是在正確的軌道上。也許你應該檢查你的用戶憑證,因爲http error response可能意味着不正確的用戶名/密碼,或者用戶沒有權限訪問資源。我有下面的代碼,我做基本的HTTP身份驗證,它工作正常。

import org.apache.http.HttpResponse; 
import org.apache.http.auth.AuthScope; 
import org.apache.http.auth.UsernamePasswordCredentials; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 


public class Authentication 
{ 

    public static void main(String[] args) 
    { 

     DefaultHttpClient dhttpclient = new DefaultHttpClient(); 

     String username = "abc"; 
     String password = "def"; 
     String host = "abc.example.com"; 
     String uri = "http://abc.example.com/protected"; 

     try 
     { 
      dhttpclient.getCredentialsProvider().setCredentials(new AuthScope(host, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password)); 
      HttpGet dhttpget = new HttpGet(uri); 

      System.out.println("executing request " + dhttpget.getRequestLine()); 
      HttpResponse dresponse = dhttpclient.execute(dhttpget); 

      System.out.println(dresponse.getStatusLine() ); 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 
     finally 
     { 
      dhttpclient.getConnectionManager().shutdown(); 
     } 

    } 

}