WowBow
WowBow

Reputation: 7603

Bad request converting curl http request to Java

I've the following request with curl that talks to Microsoft Azure services without a problem.

curl --request POST https://login.microsoftonline.com/common/oauth2/v2.0/token --data 'client_id=fe37...06-566f5c762ab2&grant_type=authorization_code&client_secret=tPv..dQfqomaG&scope=mail.read&code=OAQABAAIA...gAA'

Here is the java code that is throwing Bad Request exception:

 public String getToken(String authCode){

        try {

            HttpHeaders headers = new HttpHeaders();

            String url = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
            headers.add("client_id", "fe3..b2");
            headers.add("client_secret", "tP..aG");
            headers.add("grant_type", "authorization_code");
            headers.add("code", authCode);
            headers.add("scope", "mail.read");


            HttpEntity<?> entity = new HttpEntity<>(headers);
            RestTemplate restTemplate = new RestTemplate();

            HttpEntity<String> response = restTemplate.exchange(builder.build().toUri(), HttpMethod.POST, entity, String.class);


        }
        catch (Exception e){
            e.printStackTrace();
        }
        return null;

    }

I've also tried adding the --data section in to parameters object and I receive the same problem. I am using RestTemplate but I am open for other suggestions.

I appericiate your help.

Upvotes: 0

Views: 327

Answers (2)

yinon
yinon

Reputation: 1554

You need to send these parameters in the request entity formatted as form url encoded and also set the content-type to application/x-www-form-urlencoded.

Your body can be a string (according to your example):

String data = "client_id=fe37...06-566f5c762ab2&grant_type=authorization_code&client_secret=tPv..dQfqomaG&scope=mail.read&code=OAQABAAIA...gAA";
HttpEntity<String> entity = new HttpEntity<>(data);

Set a content type header:

headers.add("Content-Type", "application/x-www-form-urlencoded");

(Actual implementation depends on the library you use)

Upvotes: 0

Andremoniy
Andremoniy

Reputation: 34900

I suppose that problem is that in curl example you pass these parameters inside POST body, while in your java code you use headers instead. Try change it to usage of body params of entity object:

MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();     

body.add("client_id", "fe3..b2");
// ... rest params

// Note the body object as first parameter!
HttpEntity<?> entity = new HttpEntity<Object>(body, new HttpHeaders());

Upvotes: 1

Related Questions