Forum Stats

  • 3,853,788 Users
  • 2,264,269 Discussions
  • 7,905,444 Comments

Discussions

HttpURLConnection (grant_type=client_credentials) - Server returned response code 400

User12617166-Oracle
User12617166-Oracle Member Posts: 4 Employee

Need your help. Thank you.

code:

 public String getAuthToken() throws SQLException{
    ......
    HttpURLConnection httpConnection =null;
    URL url = new URL(null, tokenUrl);
    httpConnection = (HttpURLConnection) url.openConnection();
    String authString = clientId + ":" + clientSecret;

    //-- header
    httpConnection.setRequestProperty("charset", "utf-8");
    httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString(authString.getBytes()));
    httpConnection.setDoOutput(true);

    //-- body
    Map<String,String> mp = new HashMap<String,String>();
    mp.put("grant_type", "client_credentials");
    mp.put("client_id", clientId);
    mp.put("client_secret", clientSecret);
    mp.put("scope", scope);

    byte[] requestBody = buildData(mp).getBytes( StandardCharsets.UTF_8 );
    try(DataOutputStream out = new DataOutputStream(httpConnection.getOutputStream())) {
      out.write( requestBody );
    }

    if (httpConnection.getResponseCode() == 200 ){
     // success
    } else {
     // fail
    }
    ...
 }


The result of httpConnection.getResponseCode() is 400.

The result of httpConnection.getErrorSteam() is:

{"error":"invalid_request",
 "error_description":"The request contains invalid parameters or values."} 

Any idea how to find out which parameter is invalid or which parameter has invalid value?

In addition, the code works if replace

    mp.put("grant_type", "client_credentials");
    mp.put("client_id", clientId);
    mp.put("client_secret", clientSecret);

by

    mp.put("grant_type", "password");
    mp.put("username", userName);
    mp.put("password", passWord);

Thank you so much for your help.

Best Answer

Answers