It's often might be needed to get/post some info from the third party sites via HTTP.
But, most of the times you have to be signed into that web-resources.
Authentication
Authenticate via POST with parameters:
Java
public String authenticate() throws IOException, AuthenticationException {
HttpPost httpPost = new HttpPost(signInUrl);
ArrayList params = new ArrayList<>(2);
params.add(new BasicNameValuePair("username", authUser));
params.add(new BasicNameValuePair("password", authPassword));
httpPost.setEntity(new UrlEncodedFormEntity(params));
logger.info("Executing Authentication Request: " + httpPost.getRequestLine());
CloseableHttpResponse response = httpClient.execute(httpPost);
logger.info("HTML5 Authentication Response: " + response.getStatusLine());
int statusCode = response.getStatusLine().getStatusCode();
if (!HttpStatus.valueOf(statusCode).is2xxSuccessful()) {
throw new RuntimeException("Error making an Authentication request | statusCode = " + statusCode);
}
return EntityUtils.toString(response.getEntity());
}
It's nice to do it in lazy way: Whenever you do any GET/POST request, check if it's failed with 401 satusCode (UNAUTHORIZED), then authenticate and re-send previously failed request.
Make requests with pre-Authorization:
Java
BasicCredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials(authUser, authToken));
httpClient = HttpClientBuilder.create()
.setDefaultCredentialsProvider(provider).build();
public String makeRequest(URI uri, HttpRequestBase request) throws IOException {
HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(host, basicAuth);
// Add AuthCache to the execution context
HttpClientContext localContext = HttpClientContext.create();
localContext.setAuthCache(authCache);
logger.info("Executing Request: " + request.getRequestLine());
CloseableHttpResponse response = httpClient.execute(
host,
request,
localContext
);
int statusCode = response.getStatusLine().getStatusCode();
if (!HttpStatus.valueOf(statusCode).is2xxSuccessful()) {
throw new RuntimeException("Error making Request | statusCode = " + statusCode);
}
return EntityUtils.toString(response.getEntity());
}
No comments:
Post a Comment