1

HttpClient 라이브러리를 사용하여 다이제스트 인증을 수행하려고 시도하고 있지만 계속 수신합니다 : HTTP/1.1 401 Unauthorized.Apache HttpClient 다이제스트 인증에 실패했습니다.

Firefox에서 요청을 시도하면 제대로 작동하고 올바르게 응답을 얻으므로 서버 인증이 정상적으로 작동하고 있음을 알 수 있습니다.

업데이트 : moved 근무 코드가 응답 됨.

enter image description here

답변

1

다음 코드 나

import java.util.Random; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpHost; 
import org.apache.http.HttpResponse; 
import org.apache.http.auth.AuthScope; 
import org.apache.http.auth.UsernamePasswordCredentials; 
import org.apache.http.client.AuthCache; 
import org.apache.http.client.ResponseHandler; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.auth.DigestScheme; 
import org.apache.http.impl.client.BasicResponseHandler; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.client.protocol.ClientContext; 
import org.apache.http.impl.client.BasicAuthCache; 
import org.apache.http.protocol.BasicHttpContext; 
import org.apache.http.util.EntityUtils; 

/** 
* A simple example that uses HttpClient to execute an HTTP request against a 
* target site that requires user authentication. 
*/ 
public class RestClient { 

public static void main(String args[]) throws Exception { 

    HttpHost targetHost = new HttpHost("localhost", 8001, "http"); 
    DefaultHttpClient httpclient = new DefaultHttpClient(); 

    final String userName = "admin"; 
    final String password = "password"; 

    httpclient.getCredentialsProvider().setCredentials(
      new AuthScope("localhost", 8001), 
      new UsernamePasswordCredentials(userName, password)); 


    // Create AuthCache instance 
    AuthCache authCache = new BasicAuthCache(); 
    // Generate DIGEST scheme object, initialize it and add it to the local 
    // auth cache 
    DigestScheme digestAuth = new DigestScheme(); 
    // Suppose we already know the realm name 
    digestAuth.overrideParamter("realm", "some realm"); 
    // Suppose we already know the expected nonce value 
    digestAuth.overrideParamter("nonce", "whatever"); 
    authCache.put(targetHost, digestAuth); 

    // Add AuthCache to the execution context 
    BasicHttpContext localcontext = new BasicHttpContext(); 
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); 

    HttpGet httpget = new HttpGet("http://localhost:8001/rest/test"); 

    try { 
     HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); 
     HttpEntity entity = response.getEntity(); 

     System.out.println("----------------------------------------"); 
     System.out.println(response.getStatusLine()); 
     if (entity != null) { 
      System.out.println("Response content length: " + entity.getContentLength()); 
     } 
     EntityUtils.consume(entity); 
    } finally { 
     httpclient.getConnectionManager().shutdown(); 
    } 
} 
} 
근무
관련 문제