-
-
Save schatterjee4/ca0b636d7fd2394c7781025befc63726 to your computer and use it in GitHub Desktop.
preemptive http basic authentication in apache http client library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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