【问题标题】:cUrl to apache HttpClientcUrl 到 apache HttpClient
【发布时间】:2017-02-22 23:17:33
【问题描述】:

我通常使用 cUrl 来达到我的终点。但我还没有到需要考虑构建客户端的阶段。

我通常通过以下方式到达终点:

curl -u "adminaccount:adminpassword" http://localhost:8080/api/private/v1/endpoint/

假设我有以下代码

 HttpGet getRequest = new HttpGet(
        "http://localhost:8080/api/private/v1/endpoint/");

 HttpResponse response = httpClient.execute(getRequest);

现在,我显然需要传递等效的内容:

-u" adminaccount:adminpassword"

不知何故。有什么想法吗?

【问题讨论】:

  • 如果你要投反对票,至少留下评论。
  • 如何谷歌一下什么是 HTTP Authorization 标头以及如何在 HttpGet 中设置它? -- 提示:在你的情况下,它是关于 BASIC 身份验证模式...
  • 喜欢这种“你为什么不谷歌搜索”的评论——当我显然处于一个我什至不知道该搜索什么的位置时。您以前从未遇到过全新的问题吗?
  • 天哪,你都很好而且有毒,你几乎会认为我在 ruby​​ on rails 网站上问过这个问题。

标签: java apache-httpclient-4.x


【解决方案1】:

创建 HttpClient 时:

CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope("localhost", 8080),
                new UsernamePasswordCredentials("adminaccount", "adminpassword"));
        CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultCredentialsProvider(credsProvider)
                .build();

但是,是的,与其对被告知要谷歌它感到愤怒,不如去谷歌它。例如,从谷歌搜索“HttpClient 身份验证示例”开始。网站的规则很明确——“先做功课”

【讨论】:

  • 我确实google了这个,但它和curl -u不一样,因为curl -u有效,这个方法返回406的http响应。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-19
  • 1970-01-01
  • 2018-12-23
  • 1970-01-01
相关资源
最近更新 更多