Java LinkedIn OAuth2 get access token

Pass the appropriate arguments and get authetication token.

private String getLinkedInAccessToken(String authorizationCode, String clientId, String clientSecret, String redirectUri, HttpServletResponse hsr) throws Exception {
        String accessToken = "";
        try {
         
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet getRequest = new HttpGet(
                    "https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&client_id="
                            + clientId + "&client_secret=" + clientSecret + "&code=" + authorizationCode + "&redirect_uri="
                            + redirectUri);
            getRequest.addHeader("oauth2_access_token", code);
            HttpResponse response = httpClient.execute(getRequest);

            if (response.getStatusLine().getStatusCode() != 200) {
                ExceptionWriter.showMsg(hsr, "Error in get access token\n" + "Request Status Code: "+
                        response.getStatusLine().getStatusCode());
                throw new Exception("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuilder sb = new StringBuilder();
            String output;

            while ((output = br.readLine()) != null) {
                sb.append(output);
            }
            br.close();
            LOGGER.info("JSON Object" + sb);

            JSONObject jsonObject = new JSONObject(sb.toString());
            accessToken = jsonObject.getString("access_token");

            httpClient.getConnectionManager().shutdown();

        } catch (IOException | JSONException e) {
        }
        return accessToken;
    }

Include required jars in your project to run this method.

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.simple.JSONValue;
-----
-----
etc

No comments:

Post a Comment