我试图使用Apache HTTP组件与Spotify API接口。我试图发送的请求在#1下详述为here。当我使用send从bash的这个请求卷曲HTTP POST/API请求从CURL在bash上发送时失败,从Apache失败http
curl -H "Authorization: Basic SOMETOKEN" -d grant_type=client_credentials https://accounts.spotify.com/api/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();
}
错误
{ “错误”: “SERVER_ERROR”, “ERROR_DESCRIPTION”: “意外状态:400”}
的URI,该代码打印是看起来像这样
https://accounts.spotify.com/api/token?grant_type=client_credentials
和标题看起来像这样
授权:Basic SOMETOKEN
我是不是正确构造请求?还是我错过了别的? URL编码
谢谢!添加内容类型标题是我所需要的,以便让请求通过。你能解释一下为什么我需要这个,或者指出我可以在哪里了解更多关于对请求做什么的补充? –
因为此端点需要此特定内容类型。当你用curl指定'-d grant_type = client_credentials'时,你实际上使用了这个特定的内容类型:参见[this](https://curl.haxx.se/docs/manpage.html#-d) –