2012-04-04 36 views
9

tôi sử dụng Apache HttpComponents để truy cập một dịch vụ web, và don' biết làm thế nào để thiết lập người dùng/mật khẩu trong yêu cầu, đây là mã của tôi:làm thế nào để thiết lập tên người dùng/mật khẩu trong 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); 

..

nhưng vẫn nhận được lỗi trái phép 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] 

Tôi không chắc chắn nếu đúng cách để đặt người dùng/mật khẩu? bất cứ ai có thể giúp đỡ? cảm ơn.

Trả lời

4

Tôi nghĩ bạn đang đi đúng hướng. Có lẽ bạn nên kiểm tra thông tin xác thực người dùng của mình vì http error response có thể có nghĩa là tên người dùng/mật khẩu không chính xác hoặc người dùng không có đặc quyền truy cập tài nguyên. Tôi có mã dưới đây mà tôi thực hiện xác thực http cơ bản và nó hoạt động tốt.

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

    } 

} 
Các vấn đề liên quan