使用Basic Auth时,HTTPClient会发出两个请求吗? [英] HTTPClient sends out two requests when using Basic Auth?

查看:285
本文介绍了使用Basic Auth时,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 发送了两个请求。一个没有授权:基本... 标题和一个 它。第一个失败的是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 ),但是即使我对多个请求使用相同的 HttpClient ,问题仍然存在。

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 docs在这里提到它。值得庆幸的是,与上述相关的答案是一种更短更简洁的方法。

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()

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

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