gpt4 book ai didi

java - HTTP post/API 请求在 bash 上从 CURL 发送时有效,从 Apache http 发送失败

转载 作者:可可西里 更新时间:2023-11-01 16:13:27 24 4
gpt4 key购买 nike

我正在尝试使用 apache http 组件与 Spotify api 进行交互。我尝试发送的请求很详细 here在#1 下。当我使用 curl 从 bash 发送此请求时

curl -H "Authorization: Basic SOMETOKEN"-d grant_type=client_credentials https://accounts.spotify.com/api/token

我取回了网站描述的 token

然而,据我所知,以下 java 代码执行相同的请求,返回 400 错误

代码

    String encoded = "SOMETOKEN";
CloseableHttpResponse response = null;
try {
CloseableHttpClient client = HttpClients.createDefault();
URI auth = new URIBuilder()
.setScheme("https")
.setHost("accounts.spotify.com")
.setPath("/api/token")
.setParameter("grant_type", "client_credentials")
.build();

HttpPost post = new HttpPost(auth);
Header header = new BasicHeader("Authorization", "Basic " + encoded);
post.setHeader(header);
try {
response = client.execute(post);
response.getEntity().writeTo(System.out);
}
finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
}

错误

{"error":"server_error","error_description":"Unexpected status: 400"}

代码打印的 URI 如下所示

https://accounts.spotify.com/api/token?grant_type=client_credentials

标题看起来像这样

Authorization: Basic SOMETOKEN

我没有正确构建请求吗?还是我遗漏了什么?

最佳答案

对内容类型为 application/x-www-form-urlencoded 的正文数据使用表单 url 编码:

CloseableHttpClient client = HttpClients.createDefault();

HttpPost post = new HttpPost("https://accounts.spotify.com/api/token");
post.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoded);
StringEntity data = new StringEntity("grant_type=client_credentials");
post.setEntity(data);

HttpResponse response = client.execute(post);

关于java - HTTP post/API 请求在 bash 上从 CURL 发送时有效,从 Apache http 发送失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43481161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com