Showing posts with label java facebook aouth2. Show all posts
Showing posts with label java facebook aouth2. Show all posts

Java facebook oauth2 get access token

 private static final String ACCESS_TOKEN_URL = "https://graph.facebook.com/oauth/access_token?client_id=%s&redirect_uri=%s&client_secret=%s&code=%s";

private String getAccessToken(String code, String clientId, String clientSecret,  
                String redirectUri,
                HttpServletResponse hsr) throws Exception {
        String accessToken = "";
        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet getRequest = new HttpGet(String.format(ACCESS_TOKEN_URL, clientId,
                    URLEncoder.encode(redirectUri, "UTF-8"), clientSecret, code));
            getRequest.addHeader("oauth2_access_token", code);
            HttpResponse response = httpClient.execute(getRequest);

            if (response.getStatusLine().getStatusCode() != 200) {
                          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();
           
            accessToken = sb.toString();

            httpClient.getConnectionManager().shutdown();

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