HTTPClient 使用基本身份验证时发出两个请求? [英] HTTPClient sends out two requests when using Basic Auth?

查看:35
本文介绍了HTTPClient 使用基本身份验证时发出两个请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 HTTPClient 版本 4.1.2 来尝试访问需要基本身份验证的 REST over HTTP API.这是客户端代码:

I have been using HTTPClient version 4.1.2 to try to access a REST over HTTP API that requires Basic Authentication. Here is client code:

DefaultHttpClient httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager());
// Enable HTTP Basic Auth
httpClient.getCredentialsProvider().setCredentials(
    new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), 
    new UsernamePasswordCredentials(this.username, this.password));

HttpHost proxy = new HttpHost(this.proxyURI.getHost(), this.proxyURI.getPort());

httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);

当我构造一个 POST 请求时,像这样:

When I construct a POST request, like this:

HttpPost request = new HttpPost("http://my/url");
request.addHeader(new BasicHeader("Content-type", "application/atom+xml; type=entry")); // required by vendor
request.setEntity(new StringEntity("My content"));

HttpResponse response = client.execute(request);

我在 Charles Proxy 中看到有两个请求被发送.一种没有Authorization: Basic ... 标头,另一种带有.如您所料,第一个失败并返回 401,但第二个通过 201 正常运行.

I see in Charles Proxy that there are two requests being sent. One without the Authorization: Basic ... header and one with it. The first one fails with a 401, as you would expect, but the second goes through just fine with a 201.

有谁知道为什么会这样?谢谢!

Does anyone know why this happens? Thanks!

我应该清楚我已经看过这个问题,但正如您所看到的,我以相同的方式设置了 AuthScope,但并没有解决我的问题.此外,我每次发出请求时都会创建一个新的 HttpClient(尽管我使用相同的 ConnectionManager),但即使我使用相同的 HttpClientcode>多次请求,问题依旧.

I should make clear that I have already looked at this question, but as you can see I set the AuthScope the same way and it didn't solve my problem. Also, I am creating a new HttpClient every time I made a request (though I use the same ConnectionManager), but even if I use the same HttpClient for multiple requests, the problem still persists.

编辑 2:

所以看起来@LastCoder 建议的方法是这样做的.请参阅另一个问题的此答案.问题源于我对 HTTP 规范缺乏了解.我正在做的是所谓的抢占式身份验证"和 HttpClient 文档在此处提及.值得庆幸的是,上面链接的答案是一种更短、更简洁的方法.

So it looks like what @LastCoder was suggesting is the way to do. See this answer to another question. The problem stems from my lack of knowledge around the HTTP spec. What I'm looking to do is called "preemptive authentication" and the HttpClient docs mention it here. Thankfully, the answer linked to above is a much shorter and cleaner way to do it.

推荐答案

与其使用 .setCredentials() 不如直接编码 USERNAME:PASSWORD 并使用 .addHeader() 添加身份验证标头

Rather than using .setCredentials() why don't you just encode USERNAME:PASSWORD and add the authentication header with .addHeader()

这篇关于HTTPClient 使用基本身份验证时发出两个请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆