Example usage for org.apache.http.client.methods CloseableHttpResponse getAllHeaders

List of usage examples for org.apache.http.client.methods CloseableHttpResponse getAllHeaders

Introduction

In this page you can find the example usage for org.apache.http.client.methods CloseableHttpResponse getAllHeaders.

Prototype

Header[] getAllHeaders();

Source Link

Usage

From source file:com.lehman.ic9.net.httpClient.java

/**
 * Updates the Javascript response object.
 * @param info is the Javascript response object to update.
 * @param resp is a ClosableHttpResponse object with the actual response.
 * @throws NoSuchMethodException Exception
 * @throws ScriptException Exception/*  www.  j  a v a  2 s.  co  m*/
 */
private void getResponseInfo(Map<String, Object> info, CloseableHttpResponse resp)
        throws NoSuchMethodException, ScriptException {
    // Locale
    Locale jloc = resp.getLocale();
    info.put("locale", jloc.toLanguageTag());

    info.put("protocol", resp.getProtocolVersion().toString());
    info.put("protocolMajor", resp.getProtocolVersion().getMajor());
    info.put("protocolMinor", resp.getProtocolVersion().getMinor());
    info.put("statusLine", resp.getStatusLine().toString());
    info.put("statusCode", resp.getStatusLine().getStatusCode());
    info.put("statusReasonPhrase", resp.getStatusLine().getReasonPhrase());

    // Headers.
    Map<String, Object> hmap = this.eng.newObj(null);
    Header hdrs[] = resp.getAllHeaders();
    for (Header hdr : hdrs) {
        hmap.put(hdr.getName(), hdr.getValue());
    }
    info.put("headers", hmap);

    // Cookies
    Object clist = this.eng.newList();
    this.jsobj.put("cookies", clist);
    for (Cookie C : this.cs.getCookies()) {
        Object nc = this.getApacheCookie(C);
        this.eng.invokeMethod(clist, "push", nc);
    }
}

From source file:dal.arris.RequestArrisAlter.java

public RequestArrisAlter(Integer deviceId, Autenticacao autenticacao, String frequency)
        throws UnsupportedEncodingException, IOException {
    Autenticacao a = AuthFactory.getEnd();
    String auth = a.getUser() + ":" + a.getPassword();
    String url = a.getLink() + "capability/execute?capability="
            + URLEncoder.encode("\"getLanWiFiInfo\"", "UTF-8") + "&deviceId=" + deviceId + "&input="
            + URLEncoder.encode(frequency, "UTF-8");

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(1);/*from  ww  w.ja  va2 s .c  o m*/
    cm.setDefaultMaxPerRoute(1);
    HttpHost localhost = new HttpHost("10.200.6.150", 80);
    cm.setMaxPerRoute(new HttpRoute(localhost), 50);

    // Cookies
    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm)
            .setDefaultRequestConfig(globalConfig).build();

    byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("UTF-8")));
    String authHeader = "Basic " + new String(encodedAuth);

    //        CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpGet httpget = new HttpGet(url);
        httpget.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
        httpget.setHeader(HttpHeaders.CONTENT_TYPE, "text/html");
        httpget.setHeader("Cookie", "JSESSIONID=aaazqNDcHoduPbavRvVUv; AX-CARE-AGENTS-20480=HECDMIAKJABP");

        RequestConfig localConfig = RequestConfig.copy(globalConfig).setCookieSpec(CookieSpecs.STANDARD_STRICT)
                .build();

        HttpGet httpGet = new HttpGet("/");
        httpGet.setConfig(localConfig);

        //            httpget.setHeader(n);
        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);

        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            // If the response does not enclose an entity, there is no need
            // to bother about connection release
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    instream.read();
                    BufferedReader rd = new BufferedReader(
                            new InputStreamReader(response.getEntity().getContent()));
                    String line = "";
                    while ((line = rd.readLine()) != null) {
                        System.out.println(line);
                    }
                    // do something useful with the response
                } catch (IOException ex) {
                    // In case of an IOException the connection will be released
                    // back to the connection manager automatically
                    throw ex;
                } finally {
                    // Closing the input stream will trigger connection release
                    instream.close();
                }
            }
        } finally {
            response.close();
            for (Header allHeader : response.getAllHeaders()) {
                System.out.println("Nome: " + allHeader.getName() + " Valor: " + allHeader.getValue());
            }
        }
    } finally {
        httpclient.close();
    }
    httpclient.close();
}

From source file:edu.mit.scratch.Scratch.java

public static ScratchSession createSession(final String username, String password)
        throws ScratchLoginException {
    try {/*from w w w.  java 2 s  .  c o m*/
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT) // Changed due to deprecation
                .build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        lang.setDomain(".scratch.mit.edu");
        lang.setPath("/");
        cookieStore.addCookie(lang);

        final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse resp;

        final HttpUriRequest csrf = RequestBuilder.get().setUri("https://scratch.mit.edu/csrf_token/")
                .addHeader("Accept", "*/*").addHeader("Referer", "https://scratch.mit.edu")
                .addHeader("X-Requested-With", "XMLHttpRequest").build();
        resp = httpClient.execute(csrf);
        resp.close();

        String csrfToken = null;
        for (final Cookie c : cookieStore.getCookies())
            if (c.getName().equals("scratchcsrftoken"))
                csrfToken = c.getValue();

        final JSONObject loginObj = new JSONObject();
        loginObj.put("username", username);
        loginObj.put("password", password);
        loginObj.put("captcha_challenge", "");
        loginObj.put("captcha_response", "");
        loginObj.put("embed_captcha", false);
        loginObj.put("timezone", "America/New_York");
        loginObj.put("csrfmiddlewaretoken", csrfToken);
        final HttpUriRequest login = RequestBuilder.post().setUri("https://scratch.mit.edu/accounts/login/")
                .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
                .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu")
                .addHeader("Accept-Encoding", "gzip, deflate").addHeader("Accept-Language", "en-US,en;q=0.8")
                .addHeader("Content-Type", "application/json").addHeader("X-Requested-With", "XMLHttpRequest")
                .addHeader("X-CSRFToken", csrfToken).setEntity(new StringEntity(loginObj.toString())).build();
        resp = httpClient.execute(login);
        password = null;
        final BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        final JSONObject jsonOBJ = new JSONObject(
                result.toString().substring(1, result.toString().length() - 1));
        if ((int) jsonOBJ.get("success") != 1)
            throw new ScratchLoginException();
        String ssi = null;
        String sct = null;
        String e = null;
        final Header[] headers = resp.getAllHeaders();
        for (final Header header : headers)
            if (header.getName().equals("Set-Cookie")) {
                final String value = header.getValue();
                final String[] split = value.split(Pattern.quote("; "));
                for (final String s : split) {
                    if (s.contains("=")) {
                        final String[] split2 = s.split(Pattern.quote("="));
                        final String key = split2[0];
                        final String val = split2[1];
                        if (key.equals("scratchsessionsid"))
                            ssi = val;
                        else if (key.equals("scratchcsrftoken"))
                            sct = val;
                        else if (key.equals("expires"))
                            e = val;
                    }
                }
            }
        resp.close();

        return new ScratchSession(ssi, sct, e, username);
    } catch (final IOException e) {
        e.printStackTrace();
        throw new ScratchLoginException();
    }
}

From source file:org.glassfish.jersey.apache.connector.ApacheConnector.java

@Override
public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException {
    final HttpUriRequest request = getUriHttpRequest(clientRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request);

    try {/*from w w  w. jav  a  2  s.  c  o  m*/
        final CloseableHttpResponse response;
        final HttpClientContext context = HttpClientContext.create();
        if (preemptiveBasicAuth) {
            final AuthCache authCache = new BasicAuthCache();
            final BasicScheme basicScheme = new BasicScheme();
            authCache.put(getHost(request), basicScheme);
            context.setAuthCache(authCache);
        }
        response = client.execute(getHost(request), request, context);
        HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(),
                this.getClass().getName());

        final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null
                ? Statuses.from(response.getStatusLine().getStatusCode())
                : Statuses.from(response.getStatusLine().getStatusCode(),
                        response.getStatusLine().getReasonPhrase());

        final ClientResponse responseContext = new ClientResponse(status, clientRequest);
        final List<URI> redirectLocations = context.getRedirectLocations();
        if (redirectLocations != null && !redirectLocations.isEmpty()) {
            responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1));
        }

        final Header[] respHeaders = response.getAllHeaders();
        final MultivaluedMap<String, String> headers = responseContext.getHeaders();
        for (final Header header : respHeaders) {
            final String headerName = header.getName();
            List<String> list = headers.get(headerName);
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(header.getValue());
            headers.put(headerName, list);
        }

        final HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (headers.get(HttpHeaders.CONTENT_LENGTH) == null) {
                headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
            }

            final Header contentEncoding = entity.getContentEncoding();
            if (headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) {
                headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue());
            }
        }

        try {
            responseContext.setEntityStream(new HttpClientResponseInputStream(getInputStream(response)));
        } catch (final IOException e) {
            LOGGER.log(Level.SEVERE, null, e);
        }

        return responseContext;
    } catch (final Exception e) {
        throw new ProcessingException(e);
    }
}

From source file:com.github.dockerjava.jaxrs.connector.ApacheConnector.java

@Override
public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException {
    final HttpUriRequest request = getUriHttpRequest(clientRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request);

    try {//from   ww  w .  j a  v a  2 s .c o m
        final CloseableHttpResponse response;
        final HttpClientContext context = HttpClientContext.create();
        if (preemptiveBasicAuth) {
            final AuthCache authCache = new BasicAuthCache();
            final BasicScheme basicScheme = new BasicScheme();
            authCache.put(getHost(request), basicScheme);
            context.setAuthCache(authCache);
        }
        response = client.execute(getHost(request), request, context);
        HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(),
                this.getClass().getName());

        final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null
                ? Statuses.from(response.getStatusLine().getStatusCode())
                : Statuses.from(response.getStatusLine().getStatusCode(),
                        response.getStatusLine().getReasonPhrase());

        final ClientResponse responseContext = new ApacheConnectorClientResponse(status, clientRequest,
                response);
        final List<URI> redirectLocations = context.getRedirectLocations();
        if (redirectLocations != null && !redirectLocations.isEmpty()) {
            responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1));
        }

        final Header[] respHeaders = response.getAllHeaders();
        final MultivaluedMap<String, String> headers = responseContext.getHeaders();
        for (final Header header : respHeaders) {
            final String headerName = header.getName();
            List<String> list = headers.get(headerName);
            if (list == null) {
                list = new ArrayList<String>();
            }
            list.add(header.getValue());
            headers.put(headerName, list);
        }

        final HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (headers.get(HttpHeaders.CONTENT_LENGTH) == null) {
                headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
            }

            final Header contentEncoding = entity.getContentEncoding();
            if (headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) {
                headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue());
            }
        }

        try {
            responseContext.setEntityStream(new HttpClientResponseInputStream(response));
        } catch (final IOException e) {
            LOGGER.log(Level.SEVERE, null, e);
        }

        return responseContext;
    } catch (final Exception e) {
        throw new ProcessingException(e);
    }
}

From source file:run.var.teamcity.cloud.docker.client.apcon.ApacheConnector.java

@Override
public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException {
    final HttpUriRequest request = getUriHttpRequest(clientRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request);

    try {//from  ww w . jav a  2s  .c o m
        final CloseableHttpResponse response;
        final HttpClientContext context = HttpClientContext.create();
        if (preemptiveBasicAuth) {
            final AuthCache authCache = new BasicAuthCache();
            final BasicScheme basicScheme = new BasicScheme();
            authCache.put(getHost(request), basicScheme);
            context.setAuthCache(authCache);
        }
        response = client.execute(getHost(request), request, context);
        HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(),
                this.getClass().getName());

        final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null
                ? Statuses.from(response.getStatusLine().getStatusCode())
                : Statuses.from(response.getStatusLine().getStatusCode(),
                        response.getStatusLine().getReasonPhrase());

        final ClientResponse responseContext = new ClientResponse(status, clientRequest);
        final List<URI> redirectLocations = context.getRedirectLocations();
        if (redirectLocations != null && !redirectLocations.isEmpty()) {
            responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1));
        }

        final Header[] respHeaders = response.getAllHeaders();
        final MultivaluedMap<String, String> headers = responseContext.getHeaders();
        for (final Header header : respHeaders) {
            final String headerName = header.getName();
            List<String> list = headers.get(headerName);
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(header.getValue());
            headers.put(headerName, list);
        }

        final HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (headers.get(HttpHeaders.CONTENT_LENGTH) == null) {
                headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
            }

            final Header contentEncoding = entity.getContentEncoding();
            if (headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) {
                headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue());
            }
        }

        try {
            responseContext.setEntityStream(new HttpClientResponseInputStream(getInputStream(response)));
        } catch (final IOException e) {
            LOGGER.log(Level.SEVERE, null, e);
        }

        localHttpContext.set(context);
        return responseContext;
    } catch (final Exception e) {
        throw new ProcessingException(e);
    }
}

From source file:com.intuit.tank.httpclient4.TankHttpClient4.java

private void sendRequest(BaseRequest request, @Nonnull HttpRequestBase method, String requestBody) {
    String uri = null;//from w w  w .j a va 2  s  .  c om
    long waitTime = 0L;
    CloseableHttpResponse response = null;
    try {
        uri = method.getURI().toString();
        LOG.debug(request.getLogUtil().getLogMessage(
                "About to " + method.getMethod() + " request to " + uri + " with requestBody  " + requestBody,
                LogEventType.Informational));
        List<String> cookies = new ArrayList<String>();
        if (context.getCookieStore().getCookies() != null) {
            for (Cookie cookie : context.getCookieStore().getCookies()) {
                cookies.add("REQUEST COOKIE: " + cookie.toString());
            }
        }
        request.logRequest(uri, requestBody, method.getMethod(), request.getHeaderInformation(), cookies,
                false);
        setHeaders(request, method, request.getHeaderInformation());
        long startTime = System.currentTimeMillis();
        request.setTimestamp(new Date(startTime));
        response = httpclient.execute(method, context);

        // read response body
        byte[] responseBody = new byte[0];
        // check for no content headers
        if (response.getStatusLine().getStatusCode() != 203 && response.getStatusLine().getStatusCode() != 202
                && response.getStatusLine().getStatusCode() != 204) {
            try {
                InputStream httpInputStream = response.getEntity().getContent();
                responseBody = IOUtils.toByteArray(httpInputStream);
            } catch (Exception e) {
                LOG.warn("could not get response body: " + e);
            }
        }
        long endTime = System.currentTimeMillis();
        processResponse(responseBody, startTime, endTime, request, response.getStatusLine().getReasonPhrase(),
                response.getStatusLine().getStatusCode(), response.getAllHeaders());
        waitTime = endTime - startTime;
    } catch (Exception ex) {
        LOG.error(request.getLogUtil().getLogMessage(
                "Could not do " + method.getMethod() + " to url " + uri + " |  error: " + ex.toString(),
                LogEventType.IO), ex);
        throw new RuntimeException(ex);
    } finally {
        try {
            method.releaseConnection();
            if (response != null) {
                response.close();
            }
        } catch (Exception e) {
            LOG.warn("Could not release connection: " + e, e);
        }
        if (method.getMethod().equalsIgnoreCase("post")
                && request.getLogUtil().getAgentConfig().getLogPostResponse()) {
            LOG.info(request.getLogUtil()
                    .getLogMessage("Response from POST to " + request.getRequestUrl() + " got status code "
                            + request.getResponse().getHttpCode() + " BODY { " + request.getResponse().getBody()
                            + " }", LogEventType.Informational));
        }
    }
    if (waitTime != 0) {
        doWaitDueToLongResponse(request, waitTime, uri);
    }
}

From source file:net.ravendb.client.connection.ServerClient.java

public RavenJObjectIterator directStreamQuery(OperationMetadata operationMetadata, String index,
        IndexQuery query, Reference<QueryHeaderInformation> queryHeaderInfo) {
    ensureIsNotNullOrEmpty(index, "index");

    String path;//from ww  w  .j  av  a  2  s  .co  m
    HttpMethods method;

    if (query.getQuery() != null && query.getQuery().length() > convention.getMaxLengthOfQueryUsingGetUrl()) {
        path = query.getIndexQueryUrl(operationMetadata.getUrl(), index, "streams/query", false, false);
        method = HttpMethods.POST;
    } else {
        method = HttpMethods.GET;
        path = query.getIndexQueryUrl(operationMetadata.getUrl(), index, "streams/query", false);
    }

    HttpJsonRequest request = jsonRequestFactory
            .createHttpJsonRequest(new CreateHttpJsonRequestParams(this, path, method, new RavenJObject(),
                    credentialsThatShouldBeUsedOnlyInOperationsWithoutReplication, convention)
                            .addOperationHeaders(operationsHeaders))
            .addReplicationStatusHeaders(getUrl(), url, replicationInformer, convention.getFailoverBehavior(),
                    new HandleReplicationStatusChangesCallback());
    request.removeAuthorizationHeader();

    String token = getSingleAuthToken(operationMetadata);
    try {
        token = validateThatWeCanUseAuthenticateTokens(operationMetadata, token);
    } catch (Exception e) {
        request.close();
        throw new IllegalStateException(
                "Could not authenticate token for query streaming, if you are using ravendb in IIS make sure you have Anonymous Authentication enabled in the IIS configuration",
                e);
    }

    request.addOperationHeader("Single-Use-Auth-Token", token);

    CloseableHttpResponse response;

    try {
        if (HttpMethods.POST.equals(method)) {
            response = request.executeRawResponse(query.getQuery());
        } else {
            response = request.executeRawResponse();
        }
        HttpJsonRequestExtension.assertNotFailingResponse(response);
    } catch (Exception e) {
        request.close();

        if (index.startsWith("dynamic/") && request.getResponseStatusCode() == HttpStatus.SC_NOT_FOUND) {
            throw new IllegalStateException(
                    "StreamQuery does not support querying dynamic indexes. It is designed to be used with large data-sets and is unlikely to return all data-set after 15 sec of indexing, like query() does",
                    e);
        }
        throw new IllegalStateException(e.getMessage(), e);
    }

    QueryHeaderInformation queryHeaderInformation = new QueryHeaderInformation();
    Map<String, String> headers = HttpJsonRequest.extractHeaders(response.getAllHeaders());
    queryHeaderInformation.setIndex(headers.get("Raven-Index"));
    NetDateFormat sdf = new NetDateFormat();
    try {
        queryHeaderInformation.setIndexTimestamp(sdf.parse(headers.get("Raven-Index-Timestamp")));
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }

    queryHeaderInformation.setIndexEtag(Etag.parse(headers.get("Raven-Index-Etag")));
    queryHeaderInformation.setResultEtag(Etag.parse(headers.get("Raven-Result-Etag")));
    queryHeaderInformation.setStale(Boolean.valueOf(headers.get("Raven-Is-Stale")));
    queryHeaderInformation.setTotalResults(Integer.valueOf(headers.get("Raven-Total-Results")));

    queryHeaderInfo.value = queryHeaderInformation;

    return yieldStreamResults(response);
}