繁体   English   中英

从 Apache Http 组件使用 WinHttpClients

[英]Using WinHttpClients from Apache Http Components

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

}

您可以检查它是否可用。

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

如果不是,则可能是您的类路径中没有jna.jar 它取决于jna,并且如果不存在,将在上面默默地返回false ,请参见源代码

在发布前尝试使用 get(或选项)。 由于 CORS,一些网络服务器要求这样做。 https://stackoverflow.com/a/38410411/2376661

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM