Search in sources :

Example 81 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project galley by Commonjava.

the class HttpImpl method createContext.

@Override
public HttpClientContext createContext(final HttpLocation location) {
    final HttpClientContext ctx = HttpClientContext.create();
    if (location != null) {
        final CredentialsProvider creds = new BasicCredentialsProvider();
        final AuthScope as = new AuthScope(location.getHost(), location.getPort());
        if (location.getUser() != null) {
            final String password = passwords.getPassword(new PasswordEntry(location, PasswordEntry.USER_PASSWORD));
            creds.setCredentials(as, new UsernamePasswordCredentials(location.getUser(), password));
        }
        if (location.getProxyHost() != null && location.getProxyUser() != null) {
            final String password = passwords.getPassword(new PasswordEntry(location, PasswordEntry.PROXY_PASSWORD));
            creds.setCredentials(new AuthScope(location.getProxyHost(), getProxyPort(location)), new UsernamePasswordCredentials(location.getProxyUser(), password));
        }
        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) PasswordEntry(org.commonjava.maven.galley.auth.PasswordEntry) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 82 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project local-data-aragopedia by aragonopendata.

the class Utils method processURLGetApache.

public static void processURLGetApache() {
    CookieStore cookieStore = new BasicCookieStore();
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    try {
        HttpGet httpget = new HttpGet("http://bi.aragon.es/analytics/saw.dll?Go&path=/shared/IAEST-PUBLICA/Estadistica%20Local/03/030018TP&Action=Download&Options=df&NQUser=granpublico&NQPassword=granpublico");
        httpget.addHeader("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36");
        httpget.addHeader("Cookie", "sawU=granpublico; ORA_BIPS_LBINFO=153c4c924b8; ORA_BIPS_NQID=k8vgekohfuquhdg71on5hjvqbcorcupbmh4h3lu25iepaq5izOr07UFe9WiFvM3; __utma=263932892.849551431.1443517596.1457200753.1458759706.17; __utmc=263932892; __utmz=263932892.1456825145.15.6.utmcsr=alzir.dia.fi.upm.es|utmccn=(referral)|utmcmd=referral|utmcct=/kos/iaest/clase-vivienda-agregado");
        httpget.addHeader("content-type", "text/csv; charset=utf-8");
        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).setConnectTimeout(5000).setConnectionRequestTimeout(5000).setCookieSpec(CookieSpecs.DEFAULT).build();
        httpget.setConfig(requestConfig);
        HttpClientContext context = HttpClientContext.create();
        context.setCookieStore(cookieStore);
        System.out.println("executing request " + httpget.getURI());
        CloseableHttpResponse response = httpclient.execute(httpget, context);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("----------------------------------------");
            context.getRequest();
            context.getHttpRoute();
            context.getTargetAuthState();
            context.getTargetAuthState();
            context.getCookieOrigin();
            context.getCookieSpec();
            context.getUserToken();
        } finally {
            response.close();
        }
        response = httpclient.execute(httpget, context);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("----------------------------------------");
            context.getRequest();
            context.getHttpRoute();
            context.getTargetAuthState();
            context.getTargetAuthState();
            context.getCookieOrigin();
            context.getCookieSpec();
            context.getUserToken();
        } finally {
            response.close();
        }
        httpclient.close();
    } catch (ClientProtocolException e) {
        log.error("Error en el método processURLGetApache", e);
    } catch (IOException e) {
        log.error("Error en el método processURLGetApache", e);
    }
}
Also used : CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 83 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project sling by apache.

the class AbstractSlingClient method doRawRequest.

/**
     * <p>Executes a raw HTTP request, WITHOUT consuming the entity in the response. The caller is responsible for consuming the entity or
     * closing the response's InputStream in order to release the connection.
     * Otherwise, the client might run out of connections and will block</p>
     *
     * <p><b>Use this with caution and only if necessary for custom methods or for paths that must not be encoded</b>,
     * otherwise use the safe method {@link #doRequest(HttpUriRequest, List, int...)}</p>
     *
     * <p>It behaves as {@link #doStreamRequest(HttpUriRequest, List, int...)}, so the entity is not consumed.</p>
     * <p>Adds the headers and checks the response against expected status</p>
     *
     * @param method the request to be executed
     * @param uri the uri to be sent as it is (will not prepend the context path)
     * @param headers optional headers to be added to the request
     * @param expectedStatus if passed, the response status is checked against it/them, and has to match at least one of them
     * @return the response, with the entity not consumed
     * @throws ClientException if the request could not be executed
     */
public SlingHttpResponse doRawRequest(String method, String uri, List<Header> headers, int... expectedStatus) throws ClientException {
    // create context from config
    HttpClientContext context = createHttpClientContextFromConfig();
    HttpHost host = new HttpHost(getUrl().getHost(), getUrl().getPort(), getUrl().getScheme());
    HttpRequest request = new BasicHttpRequest(method, uri);
    // add headers
    if (headers != null) {
        request.setHeaders(headers.toArray(new Header[headers.size()]));
    }
    try {
        log.debug("request {} {}", method, uri);
        SlingHttpResponse response = new SlingHttpResponse(this.execute(host, request, context));
        log.debug("response {}", HttpUtils.getHttpStatus(response));
        // Check the status and throw a ClientException if it doesn't match expectedStatus, but close the entity before
        if (expectedStatus != null && expectedStatus.length > 0) {
            try {
                HttpUtils.verifyHttpStatus(response, expectedStatus);
            } catch (ClientException e) {
                // catch the exception to make sure we close the entity before re-throwing it
                response.close();
                throw e;
            }
        }
        return response;
    } catch (IOException e) {
        throw new ClientException("Could not execute http request", e);
    }
}
Also used : BasicHttpRequest(org.apache.http.message.BasicHttpRequest) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) IOException(java.io.IOException) BasicHttpRequest(org.apache.http.message.BasicHttpRequest)

Example 84 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project sling by apache.

the class AbstractSlingClient method doStreamRequest.

//
// HTTP convenience methods
//
/**
     * <p>Executes an HTTP request, WITHOUT consuming the entity in the response. The caller is responsible for consuming the entity or
     * closing the response's InputStream in order to release the connection.
     * Otherwise, the client might run out of connections and will block</p>
     *
     * <p><b>Use this with caution and only if necessary for streaming</b>, otherwise use the safe method
     * {@link #doRequest(HttpUriRequest, List, int...)}</p>
     *
     * <p>Adds the headers and checks the response against expected status</p>
     *
     * @param request the request to be executed
     * @param headers optional headers to be added to the request
     * @param expectedStatus if passed, the response status is checked against it/them, and has to match at least one of them
     * @return the response, with the entity not consumed
     * @throws ClientException if the request could not be executed
     */
public SlingHttpResponse doStreamRequest(HttpUriRequest request, List<Header> headers, int... expectedStatus) throws ClientException {
    // create context from config
    HttpClientContext context = createHttpClientContextFromConfig();
    // add headers
    if (headers != null) {
        request.setHeaders(headers.toArray(new Header[headers.size()]));
    }
    try {
        log.debug("request {} {}", request.getMethod(), request.getURI());
        SlingHttpResponse response = new SlingHttpResponse(this.execute(request, context));
        log.debug("response {}", HttpUtils.getHttpStatus(response));
        // Check the status and throw a ClientException if it doesn't match expectedStatus, but close the entity before
        if (expectedStatus != null && expectedStatus.length > 0) {
            try {
                HttpUtils.verifyHttpStatus(response, expectedStatus);
            } catch (ClientException e) {
                // catch the exception to make sure we close the entity before re-throwing it
                response.close();
                throw e;
            }
        }
        return response;
    } catch (IOException e) {
        throw new ClientException("Could not execute http request", e);
    }
}
Also used : HttpClientContext(org.apache.http.client.protocol.HttpClientContext) IOException(java.io.IOException)

Example 85 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project sling by apache.

the class StickyCookieInterceptor method process.

public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException {
    final HttpClientContext clientContext = HttpClientContext.adapt(httpContext);
    List<Cookie> cookies = clientContext.getCookieStore().getCookies();
    boolean set = (null != StickyCookieHolder.getTestStickySessionCookie());
    boolean found = false;
    ListIterator<Cookie> it = cookies.listIterator();
    while (it.hasNext()) {
        Cookie cookie = it.next();
        if (cookie.getName().equals(StickyCookieHolder.COOKIE_NAME)) {
            found = true;
            if (set) {
                // set the cookie with the value saved for each thread using the rule
                it.set(StickyCookieHolder.getTestStickySessionCookie());
            } else {
                // if the cookie is not set in TestStickySessionRule, remove it from here
                it.remove();
            }
        }
    }
    // if the cookie needs to be set from TestStickySessionRule but did not exist in the client cookie list, add it here.
    if (!found && set) {
        cookies.add(StickyCookieHolder.getTestStickySessionCookie());
    }
    BasicCookieStore cs = new BasicCookieStore();
    cs.addCookies(cookies.toArray(new Cookie[cookies.size()]));
    httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cs);
}
Also used : Cookie(org.apache.http.cookie.Cookie) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpClientContext(org.apache.http.client.protocol.HttpClientContext)

Aggregations

HttpClientContext (org.apache.http.client.protocol.HttpClientContext)160 HttpGet (org.apache.http.client.methods.HttpGet)56 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)54 IOException (java.io.IOException)48 HttpHost (org.apache.http.HttpHost)47 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)45 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)45 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)39 CredentialsProvider (org.apache.http.client.CredentialsProvider)39 URI (java.net.URI)32 HttpResponse (org.apache.http.HttpResponse)32 BasicScheme (org.apache.http.impl.auth.BasicScheme)32 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)32 AuthScope (org.apache.http.auth.AuthScope)31 AuthCache (org.apache.http.client.AuthCache)29 Test (org.junit.Test)29 HttpEntity (org.apache.http.HttpEntity)22 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)21 HttpClient (org.apache.http.client.HttpClient)18 RequestConfig (org.apache.http.client.config.RequestConfig)17