2010-01-28 67 views
3

我有將摘要請求的Restlet樣本客戶機程序的摘要認證請求。與此類似,我需要使用HttpClient api發送摘要請求的java客戶端程序。 任何人都可以向我發送示例代碼。提前致謝。Java客戶端程序發送使用的HttpClient API

 Reference reference = new Reference("http://localhost:8092/authenticate"); 
     Client client = new Client(Protocol.HTTP); 
     Request request = new Request(Method.GET, reference); 
     Response response = client.handle(request); 
     System.out.println("response: "+response.getStatus()); 

     Form form = new Form(); 
     form.add("username", "rajesh"); 
     form.add("uri", reference.getPath()); 

     // Loop over the challengeRequest objects sent by the server. 
     for (ChallengeRequest challengeRequest : response 
       .getChallengeRequests()) { 
      // Get the data from the server's response. 
      if (ChallengeScheme.HTTP_DIGEST 
        .equals(challengeRequest.getScheme())) { 
       Series<Parameter> params = challengeRequest.getParameters(); 
       form.add(params.getFirst("nonce")); 
       form.add(params.getFirst("realm")); 
       form.add(params.getFirst("domain")); 
       form.add(params.getFirst("algorithm")); 
       form.add(params.getFirst("qop")); 
      } 
     } 

     // Compute the required data 
     String a1 = Engine.getInstance().toMd5(
       "rajesh" + ":" + form.getFirstValue("realm") + ":" + "rajesh"); 
     String a2 = Engine.getInstance().toMd5(
       request.getMethod() + ":" + form.getFirstValue("uri")); 
     form.add("response", Engine.getInstance().toMd5(
       a1 + ":" + form.getFirstValue("nonce") + ":" + a2)); 

     ChallengeResponse challengeResponse = new ChallengeResponse(
       ChallengeScheme.HTTP_DIGEST, "", ""); 
     challengeResponse.setCredentialComponents(form); 

     // Send the completed request 
     request.setChallengeResponse(challengeResponse); 
     response = client.handle(request); 

     // Should be 200. 
     System.out.println(response.getStatus()); 

回答

0

你有沒有試過如下:

ChallengeResponse challengeResponse = new ChallengeResponse(challengeRequest, "rajesh", <password>); 
+0

我已經給了做工精緻的樣品。但我需要使用HttpClient api發送摘要請求的代碼。 – Rajesh 2010-01-28 10:51:47

0

在這裏你去:

HttpClient client = new HttpClient(); 
Credentials creds = new UsernamePasswordCredentials(username, password); 
client.getState().setCredentials(new AuthScope(host, port, realmName), creds); 
GetMethod get = new GetMethod(url); 
get.setDoAuthentication(true); 
client.getParams().setAuthenticationPreemptive(true); // seems to be necessary in most cases 
client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, Collections.singleton(AuthPolicy.DIGEST));//need to register DIGEST scheme not the basic 
client.getAuthSchemes().register(AuthPolicy.DIGEST, new DigestSchemeFactory()); 
client.executeMethod(get); 
result = get.getResponseBodyAsString();