Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. The request I'm trying to send is detailed here under #1. When I send this request from bash using curl

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

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"}

The URI that the code prints is looks like this

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

And the header looks like this

Authorization: Basic SOMETOKEN

Am I not constructing the request correctly? Or am I missing something else?

like image 238
Collin Dietz Avatar asked Feb 05 '26 16:02

Collin Dietz


1 Answers

Use form url-encoding for the data in the body with the content-type 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);
like image 134
Bertrand Martel Avatar answered Feb 09 '26 05:02

Bertrand Martel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!