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

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

Introduction

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

Prototype

StatusLine getStatusLine();

Source Link

Usage

From source file:io.github.theangrydev.thinhttpclient.apache.ApacheHttpClient.java

private Response adaptResponse(CloseableHttpResponse apacheResponse) throws IOException {
    StatusLine statusLine = apacheResponse.getStatusLine();
    return response(adaptHeaders(apacheResponse), statusLine.getStatusCode(), adaptBody(apacheResponse));
}

From source file:com.thoughtworks.go.agent.service.TokenRequester.java

public String getToken() throws IOException {
    LOGGER.debug("[Agent Registration] Using URL {} to get a token.", tokenURL);

    HttpRequestBase getTokenRequest = (HttpRequestBase) RequestBuilder.get(tokenURL)
            .addParameter("uuid", agentRegistry.uuid()).build();

    try {//w  w w . jav a2s  .c  o m
        CloseableHttpResponse response = httpClient.execute(getTokenRequest);
        final String responseBody = responseBody(response);
        if (response.getStatusLine().getStatusCode() == SC_OK) {
            LOGGER.info("The server has generated token for the agent.");
            return responseBody;
        } else {
            LOGGER.error("Received status code from server {}", response.getStatusLine().getStatusCode());
            LOGGER.error("Reason for failure {} ", responseBody);
            throw new RuntimeException(responseBody);
        }
    } finally {
        getTokenRequest.releaseConnection();
    }
}

From source file:com.networknt.audit.AuditHandlerTest.java

@Test
public void testAuditWithTrace() throws Exception {
    String url = "http://localhost:8080/pet";
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader(Constants.TRACEABILITY_ID, "tid");
    httpPost.setHeader(Constants.AUTHORIZATION,
            "Bearer eyJraWQiOiIxMDAiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJ1cm46Y29tOm5ldHdvcmtudDpvYXV0aDI6djEiLCJhdWQiOiJ1cm46Y29tLm5ldHdvcmtudCIsImV4cCI6MTc5MDAzNTcwOSwianRpIjoiSTJnSmdBSHN6NzJEV2JWdUFMdUU2QSI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7lh_4JSFwcHYdJMY6VfgKTHhsIGKq2uEDt3zwT56JFAePwAxENMGUTGvgceVneQzyfQsJeVGbqw55E9IfM_uSM-YcHwTfR7eSLExN4pbqzVDI353sSOvXxA98ZtJlUZKgXNE1Ngun3XFORCRIB_eH8B0FY_nT_D1Dq2WJrR-re-fbR6_va95vwoUdCofLRa4IpDfXXx19ZlAtfiVO44nw6CS8O87eGfAm7rCMZIzkWlCOFWjNHnCeRsh7CVdEH34LF-B48beiG5lM7h4N12-EME8_VDefgMjZ8eqs1ICvJMxdIut58oYbdnkwTjkA");
    try {/*w ww  .j av a 2 s .c  om*/
        StringEntity stringEntity = new StringEntity("post");
        httpPost.setEntity(stringEntity);
        CloseableHttpResponse response = client.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        Assert.assertEquals(200, statusCode);
        if (statusCode == 200) {
            String s = IOUtils.toString(response.getEntity().getContent(), "utf8");
            Assert.assertNotNull(s);
            Assert.assertEquals("OK", s);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.riotfamily.crawler.HttpClientPageLoader.java

public PageData loadPage(Href href) {
    String url = href.getResolvedUri();
    PageData pageData = new PageData(href);
    log.info("Loading page: " + url);
    HttpGet get = null;/*w  w  w  .  j  a  va  2  s  .  co m*/
    try {
        get = new HttpGet(url);
        if (StringUtils.hasText(href.getReferrerUrl())) {
            get.addHeader(ServletUtils.REFERER_HEADER, href.getReferrerUrl());
        }
        prepareMethod(get);
        CloseableHttpResponse httpResponse = client.execute(get);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        pageData.setStatusCode(statusCode);
        if (statusCode == HttpStatus.SC_OK) {
            try {
                HttpEntity entity = httpResponse.getEntity();
                if (accept(entity)) {
                    String content = EntityUtils.toString(entity, Consts.UTF_8);
                    pageData.setHtml(content);
                    Header[] headers = httpResponse.getAllHeaders();
                    for (int i = 0; i < headers.length; i++) {
                        pageData.addHeader(headers[i].getName(), headers[i].getValue());
                    }
                }
            } finally {
                httpResponse.close();
            }
        } else {
            log.info("Status: " + statusCode);
            Header[] locationHeaders = httpResponse.getHeaders("Location");
            if (locationHeaders != null && locationHeaders.length == 1) {
                pageData.setRedirectUrl(locationHeaders[0].getValue());
            } else {
                pageData.setError(httpResponse.getStatusLine().toString());
            }
        }
    } catch (Exception e) {
        pageData.setError(e.getMessage());
        log.warn(e.getMessage());
    } finally {
        try {
            if (get != null) {
                get.releaseConnection();
            }
        } catch (Exception e) {
        }
    }
    return pageData;
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.DeliveryServicesTest.java

@Test
public void itReturnsBadRequestForBadUrlQueryParameter() throws Exception {
    String encodedUrl = "httptrafficrouter01somedeliveryservicesomecdndomainfoo/stuff";
    HttpGet httpGet = new HttpGet("http://localhost:3333/crs/deliveryservices?url=" + encodedUrl);

    CloseableHttpResponse response = null;
    try {/*  w ww.  j  a  v a  2s.  co m*/
        response = closeableHttpClient.execute(httpGet);
        assertThat(response.getStatusLine().getStatusCode(), equalTo(400));
    } finally {
        if (response != null)
            response.close();
    }
}

From source file:com.github.patrickianwilson.blogs.testing.induction.integration.JaxRsIntegrationRunner.java

@Test
public void verifyJaxRsRuntimeExceptionMappingWorks() throws IOException {
    CloseableHttpClient client = HttpClients.createDefault();

    HttpGet getStatus = new HttpGet("http://localhost:8080/testing?error");

    CloseableHttpResponse statusResp = client.execute(getStatus);

    Assert.assertThat("A 500 response was expected", statusResp.getStatusLine().getStatusCode(), is(500));
}

From source file:com.github.patrickianwilson.blogs.testing.induction.integration.JaxRsIntegrationRunner.java

@Test
public void verifyJaxRsBadRequestExceptionMappingWorks() throws IOException {
    CloseableHttpClient client = HttpClients.createDefault();

    HttpGet getStatus = new HttpGet("http://localhost:8080/testing?error=badReq");

    CloseableHttpResponse statusResp = client.execute(getStatus);

    Assert.assertThat("A 400 response was expected", statusResp.getStatusLine().getStatusCode(), is(400));
}

From source file:de.avanux.smartapplianceenabler.appliance.HttpTransactionExecutor.java

/**
 * Send a HTTP request whose response has to be closed by the caller!
 * @param url/*from  w  ww. j a v a  2 s . c  o  m*/
 * @return
 */
protected CloseableHttpResponse sendHttpRequest(String url, String data, ContentType contentType,
        String username, String password) {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    if (username != null && password != null) {
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
        provider.setCredentials(AuthScope.ANY, credentials);
        httpClientBuilder.setDefaultCredentialsProvider(provider);
    }
    CloseableHttpClient client = httpClientBuilder.build();
    logger.debug("Sending HTTP request");
    logger.debug("url=" + url);
    logger.debug("data=" + data);
    logger.debug("contentType=" + contentType);
    logger.debug("username=" + username);
    logger.debug("password=" + password);
    try {
        HttpRequestBase request = null;
        if (data != null) {
            request = new HttpPost(url);
            ((HttpPost) request).setEntity(new StringEntity(data, contentType));
        } else {
            request = new HttpGet(url);
        }
        CloseableHttpResponse response = client.execute(request);
        int responseCode = response.getStatusLine().getStatusCode();
        logger.debug("Response code is " + responseCode);
        return response;
    } catch (IOException e) {
        logger.error("Error executing HTTP request.", e);
        return null;
    }
}

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

@Test
public void testPostForbidden() throws IOException {
    CloseableHttpResponse response = post("/static/");
    //status should be 403 FORBIDDEN
    assertThat(response.getStatusLine().getStatusCode(), is(403));
}

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

private CloseableHttpResponse createAndExecuteRequest(String sessionId, String url, CloseableHttpClient client)
        throws IOException {
    HttpGet request = new HttpGet(url);

    if (sessionId != null) {
        request.setHeader("sessionid", sessionId);
    }/*from   w  w  w  .  j a  v  a2s  .com*/
    CloseableHttpResponse response = client.execute(request);

    StatusLine status = response.getStatusLine();
    if (status.getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException(String.format("Cannot access resource %s: code %d", url, status.getStatusCode()));
    }
    return response;
}