Forum Discussion

avidCoder's avatar
Super Contributor
6 years ago

How to get Access Token for OAuth 2.0 using client_credentials using java code?

I have some API which requires access token to get the response. In postman we use OAuth 2.0 to get the access token by providing client username and password. In similar way, I want to fetch the new access token.

Here is the sample code which I have tried so far.


import java.util.Map;
import java.lang.reflect.Type;

// Google Gson Libraries used for Json Parsing

public class AuthGoogle {

     * @param args
     * @throws IOException 
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
         String grantType = "client_credentials";
            String applicationID = "application";
            String username = "username";
            String password = "password";
            String url = "url_link";
            HttpsURLConnection httpConn = null;
            BufferedReader in = null;

            try {

                // Create the data to send
                StringBuilder data = new StringBuilder();
                data.append("grant_type=" + URLEncoder.encode(grantType, "UTF-8"));
                data.append("&client_id=" + URLEncoder.encode(applicationID, "UTF-8"));
                data.append("&username=" + URLEncoder.encode(username, "UTF-8"));
                data.append("&password=" + URLEncoder.encode(password, "UTF-8"));

                // Create a byte array of the data to be sent
                byte[] byteArray = data.toString().getBytes("UTF-8");

                // Setup the Request
                URL request = new URL(null, url,  new;
                httpConn = (HttpsURLConnection)request.openConnection();
                httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                httpConn.setRequestProperty("Content-Length", "" + byteArray.length);

                // Write data
                OutputStream postStream = httpConn.getOutputStream();
                postStream.write(byteArray, 0, byteArray.length);

                // Send Request & Get Response
                InputStreamReader reader = new InputStreamReader(httpConn.getInputStream());
                in = new BufferedReader(reader);

                // Get the Json reponse containing the Access Token
                String json = in.readLine();
                System.out.println("Json String = " + json);

                // Parse the Json response and retrieve the Access Token
                Gson gson = new Gson();
                Type mapType  = new TypeToken<Map<String,String>>(){}.getType();
                Map<String,String> ser = gson.fromJson(json, mapType);
                String accessToken = ser.get("access_token");
                System.out.println("Access Token = " + accessToken);

            } catch ( e) {

                // This exception will be raised if the server didn't return 200 - OK
                // Retrieve more information about the error

            } finally {

                // Be sure to close out any resources or connections
                if (in != null) in.close();
                if (httpConn != null) httpConn.disconnect();


I am getting output as Connection refused: connect.

Another code I have tried is:-

import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.message.types.GrantType;

import org.apache.commons.codec.binary.Base64;

public class OltuJavaClient {

    public static final String TOKEN_REQUEST_URL = "url_link";
    public static final String CLIENT_ID = "client_id";
    public static final String CLIENT_SECRET = "client_pass";

    public static void main(String[] args) {
        try {
            OAuthClient client = new OAuthClient(new URLConnectionClient());

            OAuthClientRequest request =
                    // .setScope() here if you want to set the token scope
            request.addHeader("Accept", "application/json");
            request.addHeader("Content-Type", "application/json");
            request.addHeader("Authorization", base64EncodedBasicAuthentication());

            String token = client.accessToken(request, OAuth.HttpMethod.POST, OAuthJSONAccessTokenResponse.class).getAccessToken();

        } catch (Exception exn) {

    private static String base64EncodedBasicAuthentication() {
        // TODO Auto-generated method stub
        return null;

Here I am getting this error:- OAuthProblemException{error='unsupported_response_type', description='Invalid response! Response body is not application/json encoded', uri='null', state='null', scope='null', redirectUri='null', responseStatus=0, parameters={}}

Can we do this way? Any leads would be appreciated.

10 Replies

  • Hello avidCoder,


    The easiest way to get an access token programmarically in ReadyAPI is:

    1. Configure the OAuth 2.0 profile for a request and make sure that you can retrieve the token manually.

    2. If the selected flow requires some interaction with the internal browser, add the corresponding JavaScript code to the "Automation..." section to automate this interaction.

    3.  Add the Groovy code which accesses the configured OAuth profile and runs the token retrieval method. 


    Step #2 and #3 are described in details in this article:


    • Olga_T's avatar
      SmartBear Alumni (Retired)

      Hi all,


      NBorovykh, thank you for sharing your expertise! 

      avidCoder do the above steps work for you? Or, do you have any additional information for us?
      We are looking forward to hearing from you,



      • avidCoder's avatar
        Super Contributor

        Yes, I found the solution for my query. I used springframework code to implement this. And it was just 6-7 lines of code. Thanks for the support.