我想要的: 发送带有优先基本身份验证的 GET 请求。
请求看起来像这样:
<startURL>/app/process?job=doSomething¶m=value1,value2
而 startURL 始终是 https 链接,具体取决于环境。
看起来像这样: https://testABC.com https://prodABC.com
startURL 也像不同环境一样放置在属性文件中。
我调查的内容: http://www.baeldung.com/httpclient-4-basic-authentication
http://www.java-tips.org/other-api-tips/httpclient/how-to-use-basic-authentication.html
http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html
都包含一个
HttpHost targetHost = new HttpHost("hostname", portnumber, "scheme");
这是我遇到的麻烦。此方法也是唯一允许您将方案指定为“https”的方法。 一个问题是,我不知道端口号。我想(?)我可能只为默认端口指定 -1 以使其工作,但即使除此之外我也没有主机名,只有上面提到的 startURL。我真的不想每次都额外解析这个,同时我也不想添加另一个属性,只是为了主机名。
我四处挖掘并找到了这个片段,它看起来正是我想要的:
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://foo.com/bar");
httpGet.addHeader(BasicScheme.authenticate(
new UsernamePasswordCredentials("user", "password"),
"UTF-8", false));
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity responseEntity = httpResponse.getEntity();
来自 HTTP requests with basic authentication
它给出了完整的请求URL,只是添加了基本的header,不需要指定任何端口。只是这在 4.2 版后已被弃用:
Deprecated. (4.2) Use ContextAwareAuthScheme.authenticate( Credentials, HttpRequest, org.apache.http.protocol.HttpContext)
我找不到此方法返回基本身份验证 header 的单个示例。它还需要一个上下文作为参数,上面的片段没有。我真的不知道应该如何使用它。
那么,我想具体了解一下:
我只想设置一个包含完整链接的请求,其中包含所有内容,例如:
https://testABC.com/app/process?job=doSomething¶m=value1,value2
并将其作为执行抢占式基本身份验证的请求的参数。
有没有办法在不挖掘已弃用的方法的情况下做到这一点,它看起来怎么样?
最佳答案
我遇到了和你一样的问题。
对我有用的是:
UsernamePasswordCredentials creds = new UsernamePasswordCredentials("user", "12345");
HttpGet get = new HttpGet("https://foo.bar.com/rest");
HttpHost targetHost = new HttpHost("foo.bar.com", 443, "https");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
creds);
credsProvider.setCredentials(AuthScope.ANY,creds);
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
// Add AuthCache to the execution context
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
HttpResponse response = client.execute(targetHost, get, context);
我在以下位置找到了这个解决方案:HttpClientBuilder basic auth
关于具有完整 URI 和方案的 Java httpClient 4.3.6 基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28366969/