use of org.apache.http.impl.client.HttpClientBuilder in project wildfly by wildfly.
the class TestHttpClientUtils method promiscuousCookieHttpClientBuilder.
/**
* Same as {@link TestHttpClientUtils#promiscuousCookieHttpClient()} but instead returns a builder that can be further configured.
*
* @return {@link HttpClientBuilder} of the http client that gives free cookies to everybody
* @see TestHttpClientUtils#promiscuousCookieHttpClient()
*/
public static HttpClientBuilder promiscuousCookieHttpClientBuilder() {
HttpClientBuilder builder = HttpClients.custom();
RegistryBuilder<CookieSpecProvider> registryBuilder = CookieSpecRegistries.createDefaultBuilder();
Registry<CookieSpecProvider> promiscuousCookieSpecRegistry = registryBuilder.register("promiscuous", new PromiscuousCookieSpecProvider()).build();
builder.setDefaultCookieSpecRegistry(promiscuousCookieSpecRegistry);
RequestConfig requestConfig = RequestConfig.custom().setCookieSpec("promiscuous").build();
builder.setDefaultRequestConfig(requestConfig);
builder.setDefaultCookieStore(new PromiscuousCookieStore());
return builder;
}
use of org.apache.http.impl.client.HttpClientBuilder in project Asqatasun by Asqatasun.
the class HttpRequestHandler method getHttpClient.
private CloseableHttpClient getHttpClient(String url) {
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectionTimeout).build();
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setDefaultRequestConfig(requestConfig);
httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager());
httpClientBuilder.setUserAgent(ASQATASUN_USER_AGENT);
if (isProxySet(url)) {
LOGGER.debug(("Set proxy with " + proxyHost + " and " + proxyPort));
httpClientBuilder.setProxy(new HttpHost(proxyHost, Integer.valueOf(proxyPort)));
if (isProxyCredentialSet()) {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(proxyHost, Integer.valueOf(proxyPort)), new UsernamePasswordCredentials(proxyUser, proxyPassword));
httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
LOGGER.debug(("Set proxy credentials " + proxyHost + " and " + proxyPort + " and " + proxyUser + " and " + proxyPassword));
}
}
return httpClientBuilder.build();
}
use of org.apache.http.impl.client.HttpClientBuilder 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.impl.client.HttpClientBuilder in project intellij-community by JetBrains.
the class EduStepicClient method getBuilder.
@NotNull
static HttpClientBuilder getBuilder() {
final HttpClientBuilder builder = HttpClients.custom().setSSLContext(CertificateManager.getInstance().getSslContext()).setMaxConnPerRoute(100000).setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE);
final HttpConfigurable proxyConfigurable = HttpConfigurable.getInstance();
final List<Proxy> proxies = proxyConfigurable.getOnlyBySettingsSelector().select(URI.create(EduStepicNames.STEPIC_URL));
final InetSocketAddress address = proxies.size() > 0 ? (InetSocketAddress) proxies.get(0).address() : null;
if (address != null) {
builder.setProxy(new HttpHost(address.getHostName(), address.getPort()));
}
final ConfirmingTrustManager trustManager = CertificateManager.getInstance().getTrustManager();
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { trustManager }, new SecureRandom());
builder.setSSLContext(sslContext);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
LOG.error(e.getMessage());
}
return builder;
}
use of org.apache.http.impl.client.HttpClientBuilder in project Activiti by Activiti.
the class MuleSendActivitiBehavior method execute.
public void execute(ActivityExecution execution) throws Exception {
String endpointUrlValue = this.getStringFromField(this.endpointUrl, execution);
String languageValue = this.getStringFromField(this.language, execution);
String payloadExpressionValue = this.getStringFromField(this.payloadExpression, execution);
String resultVariableValue = this.getStringFromField(this.resultVariable, execution);
String usernameValue = this.getStringFromField(this.username, execution);
String passwordValue = this.getStringFromField(this.password, execution);
ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines();
Object payload = scriptingEngines.evaluate(payloadExpressionValue, languageValue, execution);
if (endpointUrlValue.startsWith("vm:")) {
LocalMuleClient client = this.getMuleContext().getClient();
MuleMessage message = new DefaultMuleMessage(payload, this.getMuleContext());
MuleMessage resultMessage = client.send(endpointUrlValue, message);
Object result = resultMessage.getPayload();
if (resultVariableValue != null) {
execution.setVariable(resultVariableValue, result);
}
} else {
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
if (usernameValue != null && passwordValue != null) {
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(usernameValue, passwordValue);
provider.setCredentials(new AuthScope("localhost", -1, "mule-realm"), credentials);
clientBuilder.setDefaultCredentialsProvider(provider);
}
HttpClient client = clientBuilder.build();
HttpPost request = new HttpPost(endpointUrlValue);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(payload);
oos.flush();
oos.close();
request.setEntity(new ByteArrayEntity(baos.toByteArray()));
} catch (Exception e) {
throw new ActivitiException("Error setting message payload", e);
}
byte[] responseBytes = null;
try {
// execute the POST request
HttpResponse response = client.execute(request);
responseBytes = IOUtils.toByteArray(response.getEntity().getContent());
} finally {
// release any connection resources used by the method
request.releaseConnection();
}
if (responseBytes != null) {
try {
ByteArrayInputStream in = new ByteArrayInputStream(responseBytes);
ObjectInputStream is = new ObjectInputStream(in);
Object result = is.readObject();
if (resultVariableValue != null) {
execution.setVariable(resultVariableValue, result);
}
} catch (Exception e) {
throw new ActivitiException("Failed to read response value", e);
}
}
}
this.leave(execution);
}
Aggregations