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

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

Introduction

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

Prototype

Header[] getHeaders(String str);

Source Link

Usage

From source file:fr.smile.liferay.HeaderUtils.java

/**
 * Copy headers from driverResponse to portal response
 *
 * @param driverResponse/*from  w w  w .  ja va2  s . c om*/
 * @param response
 * @param headers
 */
public static void copyHeader(CloseableHttpResponse driverResponse, ResourceResponse response,
        String... headers) {
    for (String header : headers) {

        Header[] values = driverResponse.getHeaders(header);
        if (values != null) {
            for (Header value : values) {
                response.setProperty(header, value.getValue());
            }
        }
    }

}

From source file:io.crate.rest.AdminUIIntegrationTest.java

private static void assertIsIndexResponse(CloseableHttpResponse response) throws IOException {
    //response body should not be null
    String bodyAsString = EntityUtils.toString(response.getEntity());
    assertThat(bodyAsString, is("<h1>Crate Admin</h1>\n"));
    assertThat(response.getHeaders("Content-Type")[0].getValue(), is("text/html"));
}

From source file:org.eclipse.wst.json.core.internal.download.HttpClientProvider.java

private static long getLastModified(URL url) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    try {//from w ww  .j av  a  2 s  . c  o m
        HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        Builder builder = RequestConfig.custom();
        HttpHost proxy = getProxy(target);
        if (proxy != null) {
            builder = builder.setProxy(proxy);
        }
        RequestConfig config = builder.build();
        HttpHead request = new HttpHead(url.toURI());
        request.setConfig(config);
        response = httpclient.execute(target, request);
        Header[] s = response.getHeaders("last-modified");
        if (s != null && s.length > 0) {
            String lastModified = s[0].getValue();
            return new Date(lastModified).getTime();
        }
    } catch (Exception e) {
        logWarning(e);
        return -1;
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
            }
        }
        try {
            httpclient.close();
        } catch (IOException e) {
        }
    }
    return -1;
}

From source file:bit.changepurse.wdk.http.HTTPResponse.java

private String getFromHeaders(CloseableHttpResponse apacheResponse, String key) {
    Header[] headers = apacheResponse.getHeaders(key);
    if (headers != null) {
        if (headers.length >= 1) {
            return headers[0].getValue();
        }/*from w  ww . j  a  v a2 s  . c  om*/
    }
    return "";
}

From source file:com.michaeljones.httpclient.apache.ApacheMethodClient.java

@Override
public int PutQuery(String url, List<Pair<String, String>> queryParams, StringBuilder redirect) {
    try {//  www  .  j  a  v a 2s  . co m
        HttpPut httpPut = new HttpPut();
        URIBuilder fileUri = new URIBuilder(url);

        if (queryParams != null) {
            for (Pair<String, String> queryParam : queryParams) {
                fileUri.addParameter(queryParam.getFirst(), queryParam.getSecond());
            }
        }

        httpPut = new HttpPut(fileUri.build());
        CloseableHttpResponse response = clientImpl.execute(httpPut);
        try {
            Header[] hdrs = response.getHeaders("Location");
            if (redirect != null && hdrs.length > 0) {
                String redirectLocation = hdrs[0].getValue();

                redirect.append(redirectLocation);
                LOGGER.debug("Redirect to: " + redirectLocation);
            }

            return response.getStatusLine().getStatusCode();
        } finally {
            // I believe this releases the connection to the client pool, but does not
            // close the connection.
            response.close();
        }
    } catch (IOException | URISyntaxException ex) {
        throw new RuntimeException("Apache method putQuery: " + ex.getMessage());
    }
}

From source file:com.michaeljones.httpclient.apache.ApacheMethodClient.java

@Override
public int PutFile(String url, String filePath, List<Pair<String, String>> queryParams, StringBuilder redirect)
        throws FileNotFoundException {
    try {/* w w w. ja  v  a  2  s. co  m*/
        URIBuilder fileUri = new URIBuilder(url);

        if (queryParams != null) {
            // Query params are optional. In the case of a redirect the url will contain
            // all the params.
            for (Pair<String, String> queryParam : queryParams) {
                fileUri.addParameter(queryParam.getFirst(), queryParam.getSecond());
            }
        }

        HttpPut httpPut = new HttpPut(fileUri.build());
        InputStream fileInStream = new FileInputStream(filePath);
        InputStreamEntity chunkedStream = new InputStreamEntity(fileInStream, -1,
                ContentType.APPLICATION_OCTET_STREAM);
        chunkedStream.setChunked(true);

        httpPut.setEntity(chunkedStream);

        CloseableHttpResponse response = clientImpl.execute(httpPut);
        try {
            Header[] hdrs = response.getHeaders("Location");
            if (redirect != null && hdrs.length > 0) {
                String redirectLocation = hdrs[0].getValue();

                redirect.append(redirectLocation);
                LOGGER.debug("Redirect to: " + redirectLocation);
            }

            return response.getStatusLine().getStatusCode();
        } finally {
            // I believe this releases the connection to the client pool, but does not
            // close the connection.
            response.close();
        }
    } catch (IOException | URISyntaxException ex) {
        throw new RuntimeException("Apache method putQuery: " + ex.getMessage());
    }
}

From source file:io.undertow.js.test.security.JavascriptSecurityTestCase.java

@Test
public void testAuthentication() throws IOException, ScriptException {
    final TestHttpClient client = new TestHttpClient();
    try {/*from   w  w  w  .j  av a2s .c  om*/

        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/all-auth1");
        CloseableHttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.UNAUTHORIZED, result.getStatusLine().getStatusCode());
        Header[] values = result.getHeaders(WWW_AUTHENTICATE.toString());
        String header = getAuthHeader(BASIC, values);
        assertEquals(BASIC + " realm=\"Test Realm\"", header);
        HttpClientUtils.readResponse(result);

        get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/all-auth1");
        get.addHeader(AUTHORIZATION.toString(),
                BASIC + " " + FlexBase64.encodeString("user1:password1".getBytes(), false));
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

        Assert.assertEquals("ok", HttpClientUtils.readResponse(result));

        get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/all-auth2");
        get.addHeader(AUTHORIZATION.toString(),
                BASIC + " " + FlexBase64.encodeString("user2:password2".getBytes(), false));
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

        Assert.assertEquals("ok", HttpClientUtils.readResponse(result));

        get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/admin");
        get.addHeader(AUTHORIZATION.toString(),
                BASIC + " " + FlexBase64.encodeString("user1:password1".getBytes(), false));
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

        Assert.assertEquals("ok", HttpClientUtils.readResponse(result));
        get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/admin");
        get.addHeader(AUTHORIZATION.toString(),
                BASIC + " " + FlexBase64.encodeString("user2:password2".getBytes(), false));
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.FORBIDDEN, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:org.wso2.appserver.integration.tests.carboncontext.CarbonSasSAppTestCase.java

@Test(groups = "wso2.as", description = "Access cache through the SaaS app")
public void testCacheOperationsInSaaSTestApp() throws Exception {
    String url = tempWebAppURLPrefix + "/" + APP_NAME + "/context/cache.jsp?" + "action=add" + "&cachekey="
            + cacheKey + "&cachevalue=" + cacheValue;

    HttpGet preHttpGet = new HttpGet(tempWebAppURLPrefix + "/" + APP_NAME + "/index.jsp");
    HttpGet httpGet = new HttpGet(url);
    HttpPost httpPost = new HttpPost(tempWebAppURLPrefix + "/" + APP_NAME + "/j_security_check");

    List<NameValuePair> nvps = new ArrayList<>();
    nvps.add(new BasicNameValuePair("j_username", username));
    nvps.add(new BasicNameValuePair("j_password", password));

    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nvps);
    httpPost.setEntity(urlEncodedFormEntity);

    try {/*from w w  w  . j a v a 2s . c om*/
        executeAndConsumeRequest(preHttpGet);
        executeAndConsumeRequest(httpPost);
        executeAndConsumeRequest(preHttpGet);
        executeAndConsumeRequest(httpGet);

        //View Tenant Specific Cache Values
        url = tempWebAppURLPrefix + "/" + APP_NAME + "/context/cache.jsp?" + "action=view" + "&cachekey="
                + cacheKey;
        CloseableHttpResponse closeableHttpResponse = httpClient.execute(new HttpGet(url), context);
        Header[] headers = closeableHttpResponse.getHeaders("cache-value");
        assertEquals(headers.length, 1, "Retrieved more than one value for given path");
        assertEquals(headers[0].getValue(), cacheValue, "Retrieved cache value is invalid");
    } finally {
        httpGet.releaseConnection();
        httpPost.releaseConnection();
        preHttpGet.releaseConnection();
    }
}

From source file:RGSCommonUtils.UniversalConnectionInterfaceImp.java

@Override
public String GET_Request(String p_uri, Object... p_objects) throws IOException {
    HttpGet request = new HttpGet(p_uri);
    RequestConfig config;//from  w  ww  .  j  a  v  a  2 s  . co  m
    if (this.proxy != null)
        config = RequestConfig.custom().setProxy(this.proxy).build();
    else
        config = RequestConfig.custom().build();
    request.setConfig(config);

    CloseableHttpResponse response = httpClient.execute(request);
    //        ? 
    if (response.getStatusLine().getStatusCode() == 302) {
        String newUrl = response.getHeaders("Location")[0].getValue();
        //           ?? ?  (? ?)
        request = new HttpGet(newUrl.replace("https://", "http://"));
        request.setConfig(config);
        response = httpClient.execute(request);
    }

    return responceToString(response);
}

From source file:fr.cnes.sitools.metacatalogue.resources.proxyservices.RedirectorHttps.java

/**
 * //from   w ww . j  a va 2s.c  o m
 */
private MediaType getOriginalMediaType(CloseableHttpResponse closeableResponse) {

    Header[] contentHeaders = closeableResponse.getHeaders("Content-type");
    int index = contentHeaders[0].getValue().indexOf(";");
    MediaType mediaType = new MediaType(contentHeaders[0].getValue().substring(0, index));

    return mediaType;

}