使用Apache Http Components中的WinHttpClients

时间:2016-04-05 15:28:52

标签: java apache authentication httpclient ntlm

在使用WinHttpClients和GET请求时,我已成功对需要ntlm身份验证的服务进行身份验证。但是,当我尝试POST时,我总是得到401返回代码。有人曾经成功地做过这件事吗?

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.WinHttpClients;


public class WindowsAuthPOst {

public static void main (String []args) throws Exception, IOException
{
    org.apache.log4j.BasicConfigurator.configure();
    CloseableHttpClient httpclient = WinHttpClients.createDefault();

    HttpHost target = new HttpHost("SomeHost.domain", 443, "https");

    HttpClientContext context = HttpClientContext.create();
    HttpGet httpget = new HttpGet("/some/Service.svc");
    CloseableHttpResponse response1 = httpclient.execute(target, httpget, context);
    try {
        HttpEntity entity1 = response1.getEntity();
    } finally {
        response1.close();
    }

    // Execute an expensive method next reusing the same context (and connection)
    HttpPost httppost = new HttpPost("/some/Service.svc");
    httppost.setHeader("SOAPAction", "Some Soap Action");
    httppost.setEntity(new StringEntity("Soap Payload"));
    CloseableHttpResponse response2 = httpclient.execute(target, httppost, context);
    try {
        HttpEntity entity2 = response2.getEntity();
    } finally {
        response2.close();
    }
}

}

1 个答案:

答案 0 :(得分:0)

您可以检查它是否可用。

    if (!WinHttpClients.isWinAuthAvailable()) {
        System.out.println("Integrated Win auth is not supported!!!");
    }

如果没有,可能是您的类路径中没有jna.jar。这取决于jna,如果它not there, see source code,将在上面静默返回false