HTTP post / API请求在bash上从CURL发送时起作用,从Apache http失败

时间:2017-04-18 20:00:43

标签: java http curl spotify apache-httpcomponents

我正在尝试使用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”:“意外状态:400”}

代码打印的URI看起来像这样

  

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

标题看起来像这样

  

授权:基本SOMETOKEN

我没有正确构建请求吗?或者我错过了其他什么?

1 个答案:

答案 0 :(得分:1)

使用表单url-encoding为正文中的数据添加内容类型application/x-www-form-urlencoded

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