nantitv
nantitv

Reputation: 3733

Error in getting oauth token using httpClient

I am trying to get an oauth token using http client but it results in HTTP/1.1 401 Unauthorized error. I initially tried using a curl request as follows and it was success. ( here original parameter values are not shown for the security purpose)

   curl --request POST --url oauthtokenHttpsurl  --header 'content-type: application/json' --data '{"client_id":"clientId","client_secret":"client_secret","audience":"audienceurl","grant_type":"credentials"}'

Then I tried to implement the same in java using apache httpclient as follows but it's giving a 401 Unauthorized error

   import java.io.IOException;
    import java.nio.charset.StandardCharsets;

    import org.apache.commons.io.IOUtils;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.message.BasicHeader;
    import org.apache.http.protocol.HTTP;


    public class TestOAuthPost {

    public static void main(String[] args) {
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {

            HttpPost httppost = new HttpPost("oauthtokenHttpsurl");
            JsonObject jsonObj = new JsonObject();
            jsonObj.addProperty("grant_type", "credentials");
            jsonObj.addProperty("audience", "audienceurl");
            jsonObj.addProperty("client_id", "client_id");
            jsonObj.addProperty("client_secret", "client_secret");
            StringEntity se = new StringEntity(jsonObj.toString());
            se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            httppost.setEntity(se);

            // Execute HTTP Post Request
            HttpResponse response = httpClient.execute(httppost);
            String result = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
      // 401 Unauthorized error
      } catch (IOException e) {

            System.out.println("erss");

        }
        }
    }

I am working with httpclient library and in oauth for the first time.

Could somebody please give some guidance.

Upvotes: 1

Views: 2539

Answers (1)

nantitv
nantitv

Reputation: 3733

Above code is working fine. It was my mistake, sorry for the mess. There was a copy minor spelling mistake in the client id. Anyway, I hope it will help somebody in the future

Upvotes: 2

Related Questions