我目前正在研究Java项目,但无法正常进行HTTP摘要认证。我尝试使用Apache网站,但没有帮助。我有一个需要HTTP摘要认证的站点。

        DefaultHttpClient httpclient = new DefaultHttpClient();
        String hostUrl = "http://somewebsite.com";
        String postUrl = "http://somewebsite.com/request";
        HttpPost httpPost = new HttpPost(postUrl);
        String username = "hello";
        String password = "world";
        HttpHost targetHost = new HttpHost(hostUrl);

        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(hostUrl, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        AuthCache authCache = new BasicAuthCache();

        DigestScheme digestAuth = new DigestScheme();

        digestAuth.overrideParamter("realm", "some realm");

        digestAuth.overrideParamter("nonce", "whatever");
        authCache.put(targetHost, digestAuth);

        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        // List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        // nvps.add(new BasicNameValuePair("username", "[email protected]"));
        // nvps.add(new BasicNameValuePair("password", "example"));
        // httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        HttpResponse response2 = httpclient.execute(httpPost);

最佳答案

这段代码非常适合我:

protected static void downloadDigest(URL url, FileOutputStream fos)
  throws IOException {
  HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
  CloseableHttpClient httpClient = HttpClients.createDefault();
  HttpClientContext context = HttpClientContext.create();

  String credential = url.getUserInfo();
  if (credential != null) {
    String user = credential.split(":")[0];
    String password = credential.split(":")[1];

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY,
      new UsernamePasswordCredentials(user, password));
    AuthCache authCache = new BasicAuthCache();
    DigestScheme digestScheme = new DigestScheme();
    authCache.put(targetHost, digestScheme);

    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
  }

  HttpGet httpget = new HttpGet(url.getPath());

  CloseableHttpResponse response = httpClient.execute(targetHost, httpget, context);

  try {
    ReadableByteChannel rbc = Channels.newChannel(response.getEntity().getContent());
    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
  } finally {
    response.close();
  }
}

08-05 05:03