Skip to content

Instantly share code, notes, and snippets.

@schatterjee4
Forked from kgsnipes/BasicAuth.java
Created June 16, 2016 10:17
Show Gist options
  • Save schatterjee4/ca0b636d7fd2394c7781025befc63726 to your computer and use it in GitHub Desktop.
Save schatterjee4/ca0b636d7fd2394c7781025befc63726 to your computer and use it in GitHub Desktop.
preemptive http basic authentication in apache http client library
public class BasicAuth
{
public static void main(String a[])throws Exception
{
System.out.println(getHttpResponse("78.101.139.84"));
}
public static String getHttpResponse(final String ip) throws IOException
{
String responseString = null;
final HttpHost targetHost = new HttpHost("examplehost.com", 443, "https");
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("username","password"));
final AuthCache authCache = new BasicAuthCache();
authCache.put(targetHost, new BasicScheme());
// Add AuthCache to the execution context
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
RequestConfig.Builder requestBuilder = RequestConfig.custom();
requestBuilder = requestBuilder.setAuthenticationEnabled(true);
final CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestBuilder.build())
.setDefaultCredentialsProvider(credsProvider).build();
try
{
final HttpGet httpget = new HttpGet("url");
System.out.println("Executing request " + httpget.getRequestLine());
final CloseableHttpResponse resp = httpclient.execute(httpget, context);
try
{
System.out.println("----------------------------------------");
System.out.println(resp.getStatusLine());
responseString = EntityUtils.toString(resp.getEntity());
System.out.println("the response string is :" + responseString);
EntityUtils.consume(resp.getEntity());
}
finally
{
resp.close();
}
}
finally
{
httpclient.close();
}
return responseString;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment