简体   繁体   English

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

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

I'm trying to use apache http components to interface with the Spotify api. 我正在尝试使用apache http组件与Spotify api进行交互。 The request I'm trying to send is detailed here under #1. 我试图发送请求详述这里在#1。 When I send this request from bash using curl 当我使用curl从bash发送此请求时

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

I get back a token like the website describes 我收回了网站描述的令牌

However the following java code, which as far as I can tell executes the same request, gives back a 400 error 但是,以下java代码,据我所知,执行相同的请求,返回400错误

Code

    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 错误

{"error":"server_error","error_description":"Unexpected status: 400"} {“error”:“server_error”,“error_description”:“意外状态:400”}

The URI that the code prints is looks like this 代码打印的URI如下所示

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

And the header looks like this 标题看起来像这样

Authorization: Basic SOMETOKEN 授权:基本SOMETOKEN

Am I not constructing the request correctly? 我没有正确构建请求吗? Or am I missing something else? 还是我错过了别的什么?

Use form url-encoding for the data in the body with the content-type application/x-www-form-urlencoded : 使用内容类型application/x-www-form-urlencoded对主体中的数据使用表单url-encoding:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM