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

HTTP post/API request works when sent from CURL on bash, fails from Apache http

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

从 bash 发送此请求时

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

错误

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

代码打印的 URI 如下所示

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

header 看起来像这样

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