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:com.github.patrickianwilson.blogs.testing.induction.integration.JaxRsIntegrationRunner.java

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

    HttpGet getStatus = new HttpGet("http://localhost:8080/status");

    CloseableHttpResponse statusResp = client.execute(getStatus);

    Assert.assertThat("Non 200 status response received", statusResp.getStatusLine().getStatusCode(), is(200));

}

From source file:org.assertdevelopments.promise.poc.client.StreamClient.java

public StreamResponse sendRequest(String uri, StreamRequest request) {
    logger.info("opening stream for " + uri + "...");
    try {/*  www .  j  a  va  2s  . c  om*/
        // create method
        HttpPost httpMethod = new HttpPost(uri);
        httpMethod.setHeader("User-Agent", USER_AGENT);
        httpMethod.setHeader("Accept", StreamConstants.CONTENT_TYPE);
        httpMethod.setHeader("Cache-Control", "no-cache");
        httpMethod.setHeader("Pragma", "no-cache");
        httpMethod.setHeader("Expires", "0");
        if (request != null) {
            httpMethod.setEntity(new StreamRequestEntity(request));
        }

        logger.info("streaming request...");
        CloseableHttpResponse response = httpClient.execute(httpMethod);

        // get status code
        int status = response.getStatusLine().getStatusCode();
        logger.debug("HTTP status code is " + status + ".");

        // check status code
        if (status != HttpStatus.SC_ACCEPTED) {
            throw new HttpStreamException(
                    "error while executing stream request, unexpected HTTP status code: " + status);
        }

        logger.info("streaming response...");
        return new StreamResponse(response);
    } catch (Throwable t) {
        throw new HttpStreamException("error while executing request for stream " + uri, t);
    }
}

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

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

    HttpGet getStatus = new HttpGet("http://localhost:8080/testing?url=http://input.com/long/url");

    CloseableHttpResponse statusResp = client.execute(getStatus);

    Assert.assertThat("Non 200 status response received", statusResp.getStatusLine().getStatusCode(), is(200));
    Assert.assertThat("X-Testing-Orignal-URL header was not present in the response",
            statusResp.getFirstHeader("X-Testing-Orignal-URL").getValue(), is("http://input.com/long/url"));
    Assert.assertThat("Location header was not present in the response",
            statusResp.getFirstHeader("Location").getValue(), is("http://g.og/shortened"));
}

From source file:com.networknt.traceability.TraceabilityHandlerTest.java

@Test
public void testPostWithTid() throws Exception {
    String url = "http://localhost:8080/post";
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader(Constants.TRACEABILITY_ID, "12345");
    httpPost.setHeader(Headers.CONTENT_TYPE.toString(), "application/json");
    try {/*from  w  ww  .ja  va  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("post", s);
            Header tid = response.getFirstHeader(Constants.TRACEABILITY_ID);
            Assert.assertEquals("12345", tid.getValue());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.duckling.ddl.util.RESTClient.java

public JsonObject httpPost(String url, List<NameValuePair> params) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {// w  w  w  . j  a  va2 s . c  o m
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
        httppost.setHeader("accept", "application/json");
        CloseableHttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        JsonParser jp = new JsonParser();
        JsonElement je = jp.parse(br);
        return je.getAsJsonObject();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        httpclient.close();
    }
    return null;
}

From source file:com.cognifide.aet.proxy.RestProxyServer.java

@Override
public void addHeader(String name, String value) {
    CloseableHttpClient httpClient = HttpClients.createSystem();
    try {/* w ww . ja  v a 2s.  c  o m*/
        URIBuilder uriBuilder = new URIBuilder().setScheme(HTTP).setHost(server.getAPIHost())
                .setPort(server.getAPIPort());
        // Request BMP to add header
        HttpPost request = new HttpPost(
                uriBuilder.setPath(String.format("/proxy/%d/headers", server.getProxyPort())).build());
        request.setHeader("Content-Type", "application/json");
        JSONObject json = new JSONObject();
        json.put(name, value);
        request.setEntity(new StringEntity(json.toString()));
        // Execute request
        CloseableHttpResponse response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != STATUS_CODE_OK) {
            throw new UnableToAddHeaderException(
                    "Invalid HTTP Response when attempting to add header" + statusCode);
        }
        response.close();
    } catch (Exception e) {
        throw new BMPCUnableToConnectException(String.format("Unable to connect to BMP Proxy at '%s:%s'",
                server.getAPIHost(), server.getAPIPort()), e);
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            LOGGER.warn("Unable to close httpClient", e);
        }
    }
}

From source file:com.google.cloud.tools.intellij.stats.GoogleUsageTracker.java

private void sendPing(@NotNull final List<? extends NameValuePair> postData) {
    ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
        public void run() {
            CloseableHttpClient client = HttpClientBuilder.create().setUserAgent(userAgent).build();
            HttpPost request = new HttpPost(ANALYTICS_URL);

            try {
                request.setEntity(new UrlEncodedFormEntity(postData));
                CloseableHttpResponse response = client.execute(request);
                StatusLine status = response.getStatusLine();
                if (status.getStatusCode() >= 300) {
                    logger.debug("Non 200 status code : " + status.getStatusCode() + " - "
                            + status.getReasonPhrase());
                }/*w w  w. ja v  a 2  s .co  m*/
            } catch (IOException ex) {
                logger.debug("IOException during Analytics Ping", ex.getMessage());
            } finally {
                HttpClientUtils.closeQuietly(client);
            }

        }
    });
}

From source file:io.seldon.external.ExternalPluginServer.java

@Override
public JsonNode execute(JsonNode payload, OptionsHolder options) {
    long timeNow = System.currentTimeMillis();
    URI uri = URI.create(options.getStringOption(URL_PROPERTY_NAME));
    try {//from   w  w  w . j  a  v a  2  s.  com
        URIBuilder builder = new URIBuilder().setScheme("http").setHost(uri.getHost()).setPort(uri.getPort())
                .setPath(uri.getPath()).setParameter("json", payload.toString());

        uri = builder.build();
    } catch (URISyntaxException e) {
        throw new APIException(APIException.GENERIC_ERROR);
    }
    HttpContext context = HttpClientContext.create();
    HttpGet httpGet = new HttpGet(uri);
    try {
        if (logger.isDebugEnabled())
            logger.debug("Requesting " + httpGet.getURI().toString());
        CloseableHttpResponse resp = httpClient.execute(httpGet, context);
        if (resp.getStatusLine().getStatusCode() == 200) {

            JsonFactory factory = mapper.getJsonFactory();
            JsonParser parser = factory.createJsonParser(resp.getEntity().getContent());
            JsonNode actualObj = mapper.readTree(parser);
            if (logger.isDebugEnabled())
                logger.debug(
                        "External prediction server took " + (System.currentTimeMillis() - timeNow) + "ms");
            return actualObj;
        } else {
            logger.error(
                    "Couldn't retrieve prediction from external prediction server -- bad http return code: "
                            + resp.getStatusLine().getStatusCode());
            throw new APIException(APIException.GENERIC_ERROR);
        }
    } catch (IOException e) {
        logger.error("Couldn't retrieve prediction from external prediction server - ", e);
        throw new APIException(APIException.GENERIC_ERROR);
    }

}

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

@Test
public void testSuccessfulAuthenticationFlow() throws Exception {
    //request home page /
    String location = serverRunning.getBaseUrl() + "/";
    HttpGet httpget = new HttpGet(location);
    CloseableHttpResponse response = httpclient.execute(httpget);

    assertEquals(OK.value(), response.getStatusLine().getStatusCode());

    String body = EntityUtils.toString(response.getEntity());
    EntityUtils.consume(response.getEntity());
    response.close();/*from w  w w.j av a 2  s  . c o  m*/
    httpget.completed();

    assertTrue(body.contains("/login.do"));
    assertTrue(body.contains("username"));
    assertTrue(body.contains("password"));

    String csrf = IntegrationTestUtils.extractCookieCsrf(body);

    HttpUriRequest loginPost = RequestBuilder.post().setUri(serverRunning.getBaseUrl() + "/login.do")
            .addParameter("username", testAccounts.getUserName())
            .addParameter("password", testAccounts.getPassword())
            .addParameter(CookieBasedCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, csrf).build();

    response = httpclient.execute(loginPost);
    assertEquals(FOUND.value(), response.getStatusLine().getStatusCode());
    location = response.getFirstHeader("Location").getValue();
    response.close();

    httpget = new HttpGet(location);
    response = httpclient.execute(httpget);
    assertEquals(OK.value(), response.getStatusLine().getStatusCode());

    body = EntityUtils.toString(response.getEntity());
    response.close();
    assertTrue(body.contains("Sign Out"));
}

From source file:org.commonjava.indy.httprox.RetrievedPomWithoutAuthTest.java

@Test
//    @Ignore( "TODO!" )
public void run() throws Exception {
    final String testRepo = "test";
    final PomRef pom = loadPom("simple.pom", Collections.<String, String>emptyMap());
    final String url = server.formatUrl(testRepo, pom.path);
    server.expect(url, 200, pom.pom);//from w w w .j a  v  a2  s. c o m

    final HttpGet get = new HttpGet(url);
    final CloseableHttpClient client = proxiedHttp();
    CloseableHttpResponse response = null;

    InputStream stream = null;
    try {
        response = client.execute(get);

        assertThat(response.getStatusLine().getStatusCode(), equalTo(200));

        stream = response.getEntity().getContent();
        final String resultingPom = IOUtils.toString(stream);

        assertThat(resultingPom, notNullValue());
        assertThat(resultingPom, equalTo(pom.pom));
    } finally {
        IOUtils.closeQuietly(stream);
        HttpResources.cleanupResources(get, response, client);
    }
}