Cannot call an API with Form params using JAX-RS Invocation Builder, returns a 400 status code

342 views Asked by At

Trying an example to hit a rest API , but seeing a 400 status code. Is this the correct way to call an API using form params?

import javax.json.JsonObject;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Form;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.Response;
...
public JsonObject getUserProfile() throws Exception {
    Form userform = new Form();
    userform.param("grant_type", "password")
        .param("client_id", "cexxx")                                
        .param("username", "theuser")
        .param("password", "password")
        .param("scope", "user.read openid profile offline_access");

    Client client = ClientBuilder.newClient();

    String serverUrl = "https://login.microsoftonline.com/547xx/oauth2/v2.0/token";

    WebTarget target = client.target(serverUrl);

    final Invocation.Builder invocationBuilder = target.request();
    invocationBuilder.header("Content-Type", "application/x-www-form-urlencoded");
   
    final Response response = invocationBuilder.method(
                                    HttpMethod.POST, 
                                    Entity.entity(userform, MediaType.APPLICATION_FORM_URLENCODED), 
                                    Response.class);
    
    System.out.println("r.getStatus()=" + response.getStatus());
    ...
}

The same works on Postman:

enter image description here

1

There are 1 answers

0
Suren Konathala On

Thanks Giorgi for the hint.

Actually, the code we have above to programmatically make an API call works. The issue is that we are seeing error from server side.

Using this, we are able to see the error message from server:

System.out.println(response.readEntity(String.class));

{"error":"invalid_grant","error_description":"AADSTS50034: The user account sx does not exist in the 547..b32 directory. To sign into this application, the account must be added to the directory.\r\nTrace ID: 4616...3c00\r\nCorrelation ID: 617...a01\r\nTimestamp: 2020-09-29 22:25:41Z","error_codes":[50034],"timestamp":"2020-09-29 22:25:41Z","trace_id":"461...c00","correlation_id":"617..a01","error_uri":"https://login.microsoftonline.com/error?code=50034"}