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

标签 java http curl spotify apache-httpcomponents

我正在尝试使用 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/

相关文章:

java - 了解 Integer.highestOneBit() 方法实现背后的逻辑

http - 取消状态阻止字体下载

url - 当 URL 中提供凭据时,为什么浏览器不发送 Authentication header ?

java - 服务请求后停止 HttpServer

php - 优化性能 : Many CURL requests

android - 在安卓中 curl

java - 带按钮的 table

java - Apache Jackrabbit - 我的文件在哪里?

Java多线程删除同组表

apache - 自动设置 HTTP header