Search in sources :

Example 31 with HttpClientBuilder

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;
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) CookieSpecProvider(org.apache.http.cookie.CookieSpecProvider) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder)

Example 32 with HttpClientBuilder

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();
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 33 with HttpClientBuilder

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;
    }
}
Also used : ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) ActionLibraryConfigurator(com.axway.ats.action.ActionLibraryConfigurator) ArrayList(java.util.ArrayList) DefaultProxyRoutePlanner(org.apache.http.impl.conn.DefaultProxyRoutePlanner) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) HttpHost(org.apache.http.HttpHost) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpRequest(org.apache.http.HttpRequest) HttpContext(org.apache.http.protocol.HttpContext) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Header(org.apache.http.Header) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 34 with HttpClientBuilder

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;
}
Also used : Proxy(java.net.Proxy) ConfirmingTrustManager(com.intellij.util.net.ssl.ConfirmingTrustManager) HttpConfigurable(com.intellij.util.net.HttpConfigurable) InetSocketAddress(java.net.InetSocketAddress) HttpHost(org.apache.http.HttpHost) SecureRandom(java.security.SecureRandom) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) NotNull(org.jetbrains.annotations.NotNull)

Example 35 with HttpClientBuilder

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);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) ActivitiException(org.activiti.engine.ActivitiException) ScriptingEngines(org.activiti.engine.impl.scripting.ScriptingEngines) HttpResponse(org.apache.http.HttpResponse) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) ActivitiException(org.activiti.engine.ActivitiException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) MuleMessage(org.mule.api.MuleMessage) DefaultMuleMessage(org.mule.DefaultMuleMessage) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpClient(org.apache.http.client.HttpClient) AuthScope(org.apache.http.auth.AuthScope) LocalMuleClient(org.mule.api.client.LocalMuleClient) DefaultMuleMessage(org.mule.DefaultMuleMessage) ObjectInputStream(java.io.ObjectInputStream)

Aggregations

HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)50 RequestConfig (org.apache.http.client.config.RequestConfig)17 HttpHost (org.apache.http.HttpHost)15 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)14 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)14 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)11 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)11 IOException (java.io.IOException)10 SSLContext (javax.net.ssl.SSLContext)10 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)10 CredentialsProvider (org.apache.http.client.CredentialsProvider)10 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)10 HttpClient (org.apache.http.client.HttpClient)8 PlainConnectionSocketFactory (org.apache.http.conn.socket.PlainConnectionSocketFactory)8 HttpResponse (org.apache.http.HttpResponse)7 HttpGet (org.apache.http.client.methods.HttpGet)7 HttpPost (org.apache.http.client.methods.HttpPost)7 HttpContext (org.apache.http.protocol.HttpContext)7 AuthScope (org.apache.http.auth.AuthScope)6 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)5