Skip to content

Instantly share code, notes, and snippets.

@judu
Created November 10, 2014 17:56
Show Gist options
  • Save judu/752137a4cfee9b5e616e to your computer and use it in GitHub Desktop.
Save judu/752137a4cfee9b5e616e to your computer and use it in GitHub Desktop.
Initialize Http proxy with preemptive Basic auth.
final String THE_HOST = "…";
final String THE_PORT = 8080;
final String THE_USERNAME = "…";
final String THE_PASSWORD = "…";
final AuthCache authCache = new BasicAuthCache();
final URI uri = new URI("…");
// CREATE CREDENTIALS PROVIDER, WHICH IS A MAP [HOST -> CREDS]
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(THE_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(THE_USERNAME, THE_PASSWORD));
// DONE CREATING CREDENTIALS PROVIDER.
// CREATE AUTH CACHE, AND INIT IT IN ORDER TO USE PREEMPTIVE AUTH TO PROXY.
HttpHost proxy = new HttpHost(proxyConf.host, proxyConf.port);
BasicScheme pAuth = new BasicScheme();
try {
// This is hacky: initiate the pAuth by making it believe we already issued a "Proxy-Authorization"-less request.
pAuth.processChallenge(new BasicHeader("Proxy-Authenticate", "Basic realm=\""+THE_HOST+"\""));
} catch (MalformedChallengeException e) {
logger.log(this.getClass().getName(), Level.SEVERE, "Error initializing proxy auth", e);
}
authCache.put(proxy, pAuth); // DONE AUTH CACHE FOR PROXY.
// DONE AUTH CACHE.
// CREATE CONTEXT AND INIT IT.
HttpClientContext localContext = HttpClientContext.create();
localContext.setCredentialsProvider(credsProvider);
localContext.setAuthCache(authCache);
HttpClient httpClient = HttpClients.createDefault();
final RequestConfig.Builder custom = RequestConfig.custom();
custom.setAuthenticationEnabled(true);
HttpHost proxy = new HttpHost(THE_HOST, THE_PORT);
custom.setProxy(proxy);
HttpPost post = new HttpPost(THE_TARGET_URL);
post.setConfig(custom.build());
post.setEntity(new StringEntity(data, ContentType.APPLICATION_JSON));
final HttpResponse response;
final String ans;
try {
response = httpClient.execute(post, context);
ans = EntityUtils.toString(response.getEntity());
} catch (IOException ex) {
logger.log(this.getClass().getName(), Level.SEVERE, "Error executing request", ex);
}
if(response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300) {
// Do your stuff.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment