Skip to content

Instantly share code, notes, and snippets.

@larryboymi
Last active March 28, 2017 15:22
Show Gist options
  • Save larryboymi/743e03301726a87ce02f4523ae737a17 to your computer and use it in GitHub Desktop.
Save larryboymi/743e03301726a87ce02f4523ae737a17 to your computer and use it in GitHub Desktop.
Retrieving a client_credentials token in Java (verbose, non-refactored printing version)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.net.MalformedURLException;
import java.io.IOException;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
public class ClientCredentialsSample {
public static void main(String[] args) {
try {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("id", "secret"));
AuthCache authCache = new BasicAuthCache();
// Add AuthCache to the execution context
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost("/token/url");
HttpHost target = new HttpHost("oauth.host.com", 443, "https");
authCache.put(target, new BasicScheme());
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
paramList.add(new BasicNameValuePair("grant_type", "client_credentials"));
paramList.add(new BasicNameValuePair("scope", "a_scope"));
postRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
postRequest.setEntity(new UrlEncodedFormEntity(paramList));
HttpResponse response = httpClient.execute(target, postRequest, context);
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
httpClient.getConnectionManager().shutdown();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment