use of org.apache.http.client.protocol.HttpClientContext in project indy by Commonjava.
the class HttpProxyTest method proxyContext.
protected HttpClientContext proxyContext(final String user, final String pass) {
final CredentialsProvider creds = new BasicCredentialsProvider();
creds.setCredentials(new AuthScope(HOST, proxyPort), new UsernamePasswordCredentials(user, pass));
final HttpClientContext ctx = HttpClientContext.create();
ctx.setCredentialsProvider(creds);
return ctx;
}
use of org.apache.http.client.protocol.HttpClientContext in project ats-framework by Axway.
the class HttpClient method execute.
/**
* Main execute method that sends request and receives response.
*
* @param method The POST/PUT etc. method
* @return The response
* @throws HttpException
*/
private HttpResponse execute(HttpRequestBase httpMethod) throws HttpException {
HttpClientContext localContext = null;
if (httpClient == null) {
HttpClientBuilder httpClientBuilder = HttpClients.custom();
// Add this interceptor to get the values of all HTTP headers in the request.
// Some of them are provided by the user while others are generated by Apache HTTP Components.
httpClientBuilder.addInterceptorLast(new HttpRequestInterceptor() {
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
Header[] requestHeaders = request.getAllHeaders();
actualRequestHeaders = new ArrayList<HttpHeader>();
for (Header header : requestHeaders) {
addHeaderToList(actualRequestHeaders, header.getName(), header.getValue());
}
if (debugLevel != HttpDebugLevel.NONE) {
logHTTPRequest(requestHeaders, request);
}
}
});
// Setup authentication
if (!StringUtils.isNullOrEmpty(username)) {
localContext = setupAuthentication(httpClientBuilder);
}
// Setup SSL
if (url.toLowerCase().startsWith("https")) {
setupSSL(httpClientBuilder);
}
// all important options are set, now build the HTTP client
if (AtsSystemProperties.SYSTEM_HTTP_PROXY_HOST != null && AtsSystemProperties.SYSTEM_HTTP_PROXY_PORT != null) {
HttpHost proxy = new HttpHost(AtsSystemProperties.SYSTEM_HTTP_PROXY_HOST, Integer.parseInt(AtsSystemProperties.SYSTEM_HTTP_PROXY_PORT));
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
httpClient = httpClientBuilder.setRoutePlanner(routePlanner).build();
} else {
httpClient = httpClientBuilder.build();
}
}
// Setup read and connect timeouts
httpMethod.setConfig(RequestConfig.custom().setSocketTimeout(readTimeoutSeconds * 1000).setConnectTimeout(connectTimeoutSeconds * 1000).build());
// Add HTTP headers
addHeadersToHttpMethod(httpMethod);
// Create response handler
ResponseHandler<HttpResponse> responseHandler = new ResponseHandler<HttpResponse>() {
@Override
public HttpResponse handleResponse(final org.apache.http.HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
Header[] responseHeaders = response.getAllHeaders();
List<HttpHeader> responseHeadersList = new ArrayList<HttpHeader>();
for (Header header : responseHeaders) {
addHeaderToList(responseHeadersList, header.getName(), header.getValue());
}
if ((debugLevel & HttpDebugLevel.HEADERS) == HttpDebugLevel.HEADERS) {
logHTTPResponse(responseHeaders, response);
}
try {
HttpEntity entity = response.getEntity();
if (entity == null) {
// No response body, generally have '204 No content' status
return new HttpResponse(status, response.getStatusLine().getReasonPhrase(), responseHeadersList);
} else {
if (responseBodyFilePath != null) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(responseBodyFilePath), false);
entity.writeTo(fos);
} finally {
IoUtils.closeStream(fos);
}
return new HttpResponse(status, response.getStatusLine().getReasonPhrase(), responseHeadersList);
} else {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
entity.writeTo(bos);
return new HttpResponse(status, response.getStatusLine().getReasonPhrase(), responseHeadersList, bos.toByteArray());
}
}
} finally {
if (response instanceof CloseableHttpResponse) {
IoUtils.closeStream((CloseableHttpResponse) response, "Failed to close HttpResponse");
}
}
}
};
// Send the request as POST/GET etc. and return response.
try {
return httpClient.execute(httpMethod, responseHandler, localContext);
} catch (IOException e) {
throw new HttpException("Exception occurred sending message to URL '" + actualUrl + "' with a read timeout of " + readTimeoutSeconds + " seconds and a connect timeout of " + connectTimeoutSeconds + " seconds.", e);
} finally {
// clear internal variables
ActionLibraryConfigurator actionLibraryConfigurator = ActionLibraryConfigurator.getInstance();
if (!actionLibraryConfigurator.getHttpKeepRequestHeaders()) {
this.requestHeaders.clear();
}
if (!actionLibraryConfigurator.getHttpKeepRequestParameters()) {
this.requestParameters.clear();
}
if (!actionLibraryConfigurator.getHttpKeepRequestBody()) {
this.requestBody = null;
}
this.responseBodyFilePath = null;
}
}
use of org.apache.http.client.protocol.HttpClientContext in project ats-framework by Axway.
the class HttpClient method setupAuthentication.
/**
* Set up authentication for HTTP Basic/HTTP Digest/SPNEGO.
*
* @param httpClientBuilder The client builder
* @return The context
* @throws HttpException
*/
private HttpClientContext setupAuthentication(HttpClientBuilder httpClientBuilder) throws HttpException {
HttpClientContext localContext = null;
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password));
httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
if (authType == AuthType.always) {
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local
// auth cache
BasicScheme basicAuth = new BasicScheme();
URL uri = null;
try {
uri = new URL(url);
} catch (MalformedURLException e) {
throw new HttpException("Exception occurred creating URL from '" + url + "'.", e);
}
HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getProtocol());
authCache.put(target, basicAuth);
// Add AuthCache to the execution context
localContext = HttpClientContext.create();
localContext.setAuthCache(authCache);
} else {
if (!StringUtils.isNullOrEmpty(kerberosServicePrincipalName)) {
GssClient gssClient = new GssClient(username, password, kerberosClientKeytab, krb5ConfFile);
AuthSchemeProvider nsf = new SPNegoSchemeFactory(gssClient, kerberosServicePrincipalName, kerberosServicePrincipalType);
final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, nsf).build();
httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
}
}
return localContext;
}
use of org.apache.http.client.protocol.HttpClientContext in project opennms by OpenNMS.
the class RestSessionIT method queryUri.
private Header[] queryUri(final String uri, final String header) throws IOException {
final HttpGet httpGet = new HttpGet(getBaseUrl() + uri);
final HttpHost targetHost = new HttpHost(httpGet.getURI().getHost(), httpGet.getURI().getPort(), httpGet.getURI().getScheme());
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("admin", "admin"));
final AuthCache authCache = new BasicAuthCache();
final BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
final CloseableHttpResponse closeableHttpResponse = HttpClients.createDefault().execute(targetHost, httpGet, context);
closeableHttpResponse.close();
return closeableHttpResponse.getHeaders(header);
}
use of org.apache.http.client.protocol.HttpClientContext in project lucene-solr by apache.
the class HttpSolrClient method executeMethod.
protected NamedList<Object> executeMethod(HttpRequestBase method, final ResponseParser processor) throws SolrServerException {
method.addHeader("User-Agent", AGENT);
org.apache.http.client.config.RequestConfig.Builder requestConfigBuilder = HttpClientUtil.createDefaultRequestConfigBuilder();
if (soTimeout != null) {
requestConfigBuilder.setSocketTimeout(soTimeout);
}
if (connectionTimeout != null) {
requestConfigBuilder.setConnectTimeout(connectionTimeout);
}
if (followRedirects != null) {
requestConfigBuilder.setRedirectsEnabled(followRedirects);
}
method.setConfig(requestConfigBuilder.build());
HttpEntity entity = null;
InputStream respBody = null;
boolean shouldClose = true;
try {
// Execute the method.
HttpClientContext httpClientRequestContext = HttpClientUtil.createNewHttpClientRequestContext();
final HttpResponse response = httpClient.execute(method, httpClientRequestContext);
int httpStatus = response.getStatusLine().getStatusCode();
// Read the contents
entity = response.getEntity();
respBody = entity.getContent();
Header ctHeader = response.getLastHeader("content-type");
String contentType;
if (ctHeader != null) {
contentType = ctHeader.getValue();
} else {
contentType = "";
}
// handle some http level checks before trying to parse the response
switch(httpStatus) {
case HttpStatus.SC_OK:
case HttpStatus.SC_BAD_REQUEST:
case // 409
HttpStatus.SC_CONFLICT:
break;
case HttpStatus.SC_MOVED_PERMANENTLY:
case HttpStatus.SC_MOVED_TEMPORARILY:
if (!followRedirects) {
throw new SolrServerException("Server at " + getBaseURL() + " sent back a redirect (" + httpStatus + ").");
}
break;
default:
if (processor == null || "".equals(contentType)) {
throw new RemoteSolrException(baseUrl, httpStatus, "non ok status: " + httpStatus + ", message:" + response.getStatusLine().getReasonPhrase(), null);
}
}
if (processor == null || processor instanceof InputStreamResponseParser) {
// no processor specified, return raw stream
NamedList<Object> rsp = new NamedList<>();
rsp.add("stream", respBody);
rsp.add("closeableResponse", response);
// Only case where stream should not be closed
shouldClose = false;
return rsp;
}
String procCt = processor.getContentType();
if (procCt != null) {
String procMimeType = ContentType.parse(procCt).getMimeType().trim().toLowerCase(Locale.ROOT);
String mimeType = ContentType.parse(contentType).getMimeType().trim().toLowerCase(Locale.ROOT);
if (!procMimeType.equals(mimeType)) {
// unexpected mime type
String msg = "Expected mime type " + procMimeType + " but got " + mimeType + ".";
Header encodingHeader = response.getEntity().getContentEncoding();
String encoding;
if (encodingHeader != null) {
encoding = encodingHeader.getValue();
} else {
// try UTF-8
encoding = "UTF-8";
}
try {
msg = msg + " " + IOUtils.toString(respBody, encoding);
} catch (IOException e) {
throw new RemoteSolrException(baseUrl, httpStatus, "Could not parse response with encoding " + encoding, e);
}
throw new RemoteSolrException(baseUrl, httpStatus, msg, null);
}
}
NamedList<Object> rsp = null;
String charset = EntityUtils.getContentCharSet(response.getEntity());
try {
rsp = processor.processResponse(respBody, charset);
} catch (Exception e) {
throw new RemoteSolrException(baseUrl, httpStatus, e.getMessage(), e);
}
if (httpStatus != HttpStatus.SC_OK) {
NamedList<String> metadata = null;
String reason = null;
try {
NamedList err = (NamedList) rsp.get("error");
if (err != null) {
reason = (String) err.get("msg");
if (reason == null) {
reason = (String) err.get("trace");
}
metadata = (NamedList<String>) err.get("metadata");
}
} catch (Exception ex) {
}
if (reason == null) {
StringBuilder msg = new StringBuilder();
msg.append(response.getStatusLine().getReasonPhrase()).append("\n\n").append("request: ").append(method.getURI());
reason = java.net.URLDecoder.decode(msg.toString(), UTF_8);
}
RemoteSolrException rss = new RemoteSolrException(baseUrl, httpStatus, reason, null);
if (metadata != null)
rss.setMetadata(metadata);
throw rss;
}
return rsp;
} catch (ConnectException e) {
throw new SolrServerException("Server refused connection at: " + getBaseURL(), e);
} catch (SocketTimeoutException e) {
throw new SolrServerException("Timeout occured while waiting response from server at: " + getBaseURL(), e);
} catch (IOException e) {
throw new SolrServerException("IOException occured when talking to server at: " + getBaseURL(), e);
} finally {
if (shouldClose) {
Utils.consumeFully(entity);
}
}
}
Aggregations