Search in sources :

Example 31 with HttpClientContext

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;
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) AuthScope(org.apache.http.auth.AuthScope) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 32 with HttpClientContext

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;
    }
}
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 33 with HttpClientContext

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;
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) MalformedURLException(java.net.MalformedURLException) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) SPNegoSchemeFactory(com.axway.ats.core.gss.spnego.SPNegoSchemeFactory) URL(java.net.URL) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) GssClient(com.axway.ats.core.gss.GssClient) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider)

Example 34 with HttpClientContext

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);
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) HttpGet(org.apache.http.client.methods.HttpGet) AuthScope(org.apache.http.auth.AuthScope) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) AuthCache(org.apache.http.client.AuthCache) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 35 with HttpClientContext

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);
        }
    }
}
Also used : HttpEntity(org.apache.http.HttpEntity) InputStream(java.io.InputStream) NamedList(org.apache.solr.common.util.NamedList) SolrServerException(org.apache.solr.client.solrj.SolrServerException) HttpResponse(org.apache.http.HttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) IOException(java.io.IOException) SolrServerException(org.apache.solr.client.solrj.SolrServerException) SolrException(org.apache.solr.common.SolrException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SocketTimeoutException(java.net.SocketTimeoutException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) SocketTimeoutException(java.net.SocketTimeoutException) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) ConnectException(java.net.ConnectException)

Aggregations

HttpClientContext (org.apache.http.client.protocol.HttpClientContext)44 IOException (java.io.IOException)18 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)17 HttpHost (org.apache.http.HttpHost)16 AuthScope (org.apache.http.auth.AuthScope)15 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)15 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)13 CredentialsProvider (org.apache.http.client.CredentialsProvider)12 BasicScheme (org.apache.http.impl.auth.BasicScheme)11 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)11 AuthCache (org.apache.http.client.AuthCache)10 HttpGet (org.apache.http.client.methods.HttpGet)10 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)10 HttpResponse (org.apache.http.HttpResponse)9 Header (org.apache.http.Header)8 URI (java.net.URI)6 HttpEntity (org.apache.http.HttpEntity)6 HttpContext (org.apache.http.protocol.HttpContext)5 SocketTimeoutException (java.net.SocketTimeoutException)4 HttpRequest (org.apache.http.HttpRequest)4