使用 Apache Http 组件中的 WinHttpClients
Posted
技术标签:
【中文标题】使用 Apache Http 组件中的 WinHttpClients【英文标题】:Using WinHttpClients from Apache Http Components 【发布时间】:2016-07-25 15:39:32 【问题描述】:当使用 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】:您可以检查它是否可用。
if (!WinHttpClients.isWinAuthAvailable())
System.out.println("Integrated Win auth is not supported!!!");
如果没有,可能是您的类路径中没有jna.jar。它取决于 jna,如果它是 not there, see source code,它将在上面静默返回 false
。
【讨论】:
它可用是因为它对 GET 有效,但对 POST 无效【参考方案2】:在发布前尝试使用 get(或 options)。由于 CORS,一些网络服务器需要这样做。 https://***.com/a/38410411/2376661
【讨论】:
虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review以上是关于使用 Apache Http 组件中的 WinHttpClients的主要内容,如果未能解决你的问题,请参考以下文章
Apache Camel http 到 http 路由(有可能吗?)