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

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

Introduction

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

Prototype

Header getFirstHeader(String str);

Source Link

Usage

From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java

/**
 * Perform DELETE request against an RTC server.
 * @param serverURI The RTC server//from  w ww  .  java2  s . co  m
 * @param uri The relative URI for the DELETE. It is expected that it is already encoded if necessary.
 * @param userId The userId to authenticate as
 * @param password The password to authenticate with
 * @param timeout The timeout period for the connection (in seconds)
 * @param httpContext The context from the login if cycle is being managed by the caller
 * Otherwise <code>null</code> and this call will handle the login.
 * @param listener The listener to report errors to.
 * May be <code>null</code> if there is no listener.
 * @return The HttpContext for the request. May be reused in subsequent requests
 * for the same user
 * @throws IOException Thrown if things go wrong
 * @throws InvalidCredentialsException
 * @throws GeneralSecurityException 
 */
public static HttpClientContext performDelete(String serverURI, String uri, String userId, String password,
        int timeout, HttpClientContext httpContext, TaskListener listener)
        throws IOException, InvalidCredentialsException, GeneralSecurityException {

    CloseableHttpClient httpClient = getClient();
    String fullURI = getFullURI(serverURI, uri);

    HttpDelete delete = getDELETE(fullURI, timeout);
    if (httpContext == null) {
        httpContext = createHttpContext();
    }

    LOGGER.finer("DELETE: " + delete.getURI()); //$NON-NLS-1$
    CloseableHttpResponse response = httpClient.execute(delete, httpContext);
    try {
        int statusCode = response.getStatusLine().getStatusCode();
        Header locationHeader = response.getFirstHeader(LOCATION);
        boolean redirectsFollowed = false;
        int paranoia = 100;
        while (statusCode == 302 && locationHeader != null && paranoia > 0) {
            redirectsFollowed = true;
            // follow the redirects. Eventually we will get to a point where we can authenticate
            closeResponse(response);
            String redirectURI = locationHeader.getValue();
            HttpGet request = getGET(redirectURI, timeout);
            LOGGER.finer("DELETE following redirect before auth: " + request.getURI()); //$NON-NLS-1$
            response = httpClient.execute(request, httpContext);
            statusCode = response.getStatusLine().getStatusCode();
            locationHeader = response.getFirstHeader(LOCATION);
            paranoia--;
        }

        // based on the response do any authentication. If authentication requires
        // the request to be performed again (i.e. Basic auth) re-issue request
        response = authenticateIfRequired(response, httpClient, httpContext, serverURI, userId, password,
                timeout, listener);

        if (response != null) {
            checkDeleteResponse(response, fullURI, serverURI, userId, listener);
        }

        // retry delete request if we have to do authentication or we followed a redirect to a Get
        if (redirectsFollowed || response == null) {
            // Do the actual delete
            paranoia = 100;
            do {
                // follow the redirects. Eventually we will get to a point where we can authenticate
                closeResponse(response);
                HttpDelete request = getDELETE(fullURI, timeout);
                LOGGER.finer("DELETE following redirect after auth: " + request.getURI()); //$NON-NLS-1$
                response = httpClient.execute(request, httpContext);
                statusCode = response.getStatusLine().getStatusCode();
                locationHeader = response.getFirstHeader(LOCATION);
                if (locationHeader != null) {
                    fullURI = locationHeader.getValue();
                }
                paranoia--;
            } while (statusCode == 302 && locationHeader != null && paranoia > 0);
            checkDeleteResponse(response, fullURI, serverURI, userId, listener);
        }

        return httpContext;
    } finally {
        closeResponse(response);
    }
}

From source file:com.synopsys.integration.blackduck.rest.CredentialsBlackDuckHttpClient.java

@Override
protected void completeAuthenticationRequest(HttpUriRequest request, Response response) {
    if (response.isStatusCodeOkay()) {
        CloseableHttpResponse actualResponse = response.getActualResponse();
        Header csrfHeader = actualResponse.getFirstHeader(RestConstants.X_CSRF_TOKEN);
        String csrfHeaderValue = csrfHeader.getValue();
        if (null != csrfHeaderValue) {
            authenticationSupport.addAuthenticationHeader(this, request, RestConstants.X_CSRF_TOKEN,
                    csrfHeaderValue);//w  w w . j  av  a2 s. c  om
        } else {
            logger.error("No CSRF token found when authenticating.");
        }
    }
}

From source file:org.mule.service.http.impl.functional.server.HttpServerTransferTestCase.java

protected String getHeaderValue(CloseableHttpResponse response, String name) {
    Header header = response.getFirstHeader(name);
    return header != null ? header.getValue() : null;
}

From source file:org.ow2.proactive.http.CommonHttpResourceDownloader.java

public UrlContent getResourceContent(String sessionId, String url, boolean insecure) throws IOException {

    CommonHttpClientBuilder builder = new CommonHttpClientBuilder().maxConnections(CONNECTION_POOL_SIZE)
            .useSystemProperties().insecure(insecure);
    try (CloseableHttpClient client = builder.build()) {
        CloseableHttpResponse response = createAndExecuteRequest(sessionId, url, client);

        Header contentDispositionHeader = response.getFirstHeader("Content-Disposition");
        String filename;//from   w w  w. j  av a2 s .com
        if (contentDispositionHeader != null
                && contentDispositionHeader.getValue().matches(CONTENT_DISPOSITIOB_REGEXP)) {
            filename = contentDispositionHeader.getValue().replaceFirst(CONTENT_DISPOSITIOB_REGEXP, "$1");
        } else {
            filename = FileUtils.getFileNameWithExtension(new URL(url));
        }
        return new UrlContent(readContent(response.getEntity().getContent()), filename);
    }
}

From source file:org.cloudfoundry.identity.uaa.integration.FormLoginIntegrationTests.java

@Test
public void testUnauthenticatedRedirect() throws Exception {
    String location = serverRunning.getBaseUrl() + "/";
    HttpGet httpget = new HttpGet(location);
    httpget.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build());
    CloseableHttpResponse response = httpclient.execute(httpget);
    assertEquals(FOUND.value(), response.getStatusLine().getStatusCode());
    location = response.getFirstHeader("Location").getValue();
    response.close();//from ww  w. j ava 2 s  .co  m
    httpget.completed();
    assertTrue(location.contains("/login"));
}

From source file:org.jboss.additional.testsuite.jdkall.present.web.servlet.headers.CookieHeaderServletTestCase.java

@Test
@OperateOnDeployment(DEPLOYMENT)/*from   w w w .j  av  a 2  s.  com*/
public void cookieHeaderTest(@ArquillianResource URL url) throws Exception {
    URL testURL = new URL(url.toString() + "cookieHeaderServlet");

    final HttpGet request = new HttpGet(testURL.toString());
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    CloseableHttpResponse response = null;

    response = httpClient.execute(request);
    Assert.assertTrue("Wrong Set-Cookie header format.",
            response.getFirstHeader("Set-Cookie").getValue().contains("\"example cookie\""));
    IOUtils.closeQuietly(response);
    httpClient.close();

}

From source file:co.paralleluniverse.comsat.webactors.AbstractWebActorTest.java

@Test
public void testHttpMsg() throws IOException, InterruptedException, ExecutionException {
    final HttpGet httpGet = new HttpGet("http://localhost:8080");
    try (final CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(requestConfig)
            .build()) {/*from  w  ww .  j  a v  a 2  s. c  om*/
        final CloseableHttpResponse res = client.execute(httpGet);
        assertEquals(200, res.getStatusLine().getStatusCode());
        assertEquals("text/html", res.getFirstHeader("Content-Type").getValue());
        assertEquals("12", res.getFirstHeader("Content-Length").getValue());
        assertEquals("httpResponse", EntityUtils.toString(res.getEntity()));
    }
}

From source file:ch.ralscha.extdirectspring_itest.MyModelControlerTest.java

@Test
public void testApi() throws IOException {
    HttpGet g = new HttpGet("http://localhost:9998/controller/api.js?group=itest_base");
    CloseableHttpResponse response = this.client.execute(g);
    try {//  w w  w . j  av  a 2s.  c  o  m
        String responseString = EntityUtils.toString(response.getEntity());
        String contentType = response.getFirstHeader("Content-Type").getValue();
        ApiControllerTest.compare(responseString, contentType, api(), ApiRequestParams.builder().build());
        SimpleServiceTest.assertCacheHeaders(response, false);
    } finally {
        IOUtils.closeQuietly(response);
    }
}

From source file:ch.ralscha.extdirectspring_itest.MyModelControlerTest.java

@Test
public void testApiDebug() throws IOException {
    HttpGet g = new HttpGet("http://localhost:9998/controller/api-debug.js?group=itest_base");
    CloseableHttpResponse response = this.client.execute(g);
    try {/*  w  w  w. j a v  a 2 s .co m*/
        String responseString = EntityUtils.toString(response.getEntity());
        String contentType = response.getFirstHeader("Content-Type").getValue();
        ApiControllerTest.compare(responseString, contentType, api(), ApiRequestParams.builder().build());
        SimpleServiceTest.assertCacheHeaders(response, false);
    } finally {
        IOUtils.closeQuietly(response);
    }
}