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:de.intevation.irix.ImageClient.java

/** Obtains a Report from mapfish-print service.
 *
 * @param imageUrl The url to send the request to.
 * @param timeout the timeout for the httpconnection.
 *
 * @return byte[] with the report./*from w w w  . jav a2s .co  m*/
 *
 * @throws IOException if communication with print service failed.
 * @throws ImageException if the print job failed.
 */
public static byte[] getImage(String imageUrl, int timeout) throws IOException, ImageException {

    RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).build();

    CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();

    HttpGet get = new HttpGet(imageUrl);
    CloseableHttpResponse resp = client.execute(get);

    StatusLine status = resp.getStatusLine();

    byte[] retval = null;
    try {
        HttpEntity respEnt = resp.getEntity();
        InputStream in = respEnt.getContent();
        if (in != null) {
            try {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buf = new byte[BYTE_ARRAY_SIZE];
                int r;
                while ((r = in.read(buf)) >= 0) {
                    out.write(buf, 0, r);
                }
                retval = out.toByteArray();
            } finally {
                in.close();
                EntityUtils.consume(respEnt);
            }
        }
    } finally {
        resp.close();
    }

    if (status.getStatusCode() < HttpURLConnection.HTTP_OK
            || status.getStatusCode() >= HttpURLConnection.HTTP_MULT_CHOICE) {
        if (retval != null) {
            throw new ImageException(new String(retval));
        } else {
            throw new ImageException("Communication with print service '" + imageUrl + "' failed."
                    + "\nNo response from print service.");
        }
    }
    return retval;
}

From source file:io.undertow.server.handlers.URLDecodingHandlerTestCase.java

private static String getResponseString(CloseableHttpResponse response) throws IOException {
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    return IOUtils.toString(response.getEntity().getContent(), "UTF-8");
}

From source file:org.openo.nfvo.monitor.umc.monitor.common.HttpClientUtil.java

/**
 * @Title httpPost//from   w  w  w . j  a  v a2  s .  c o  m
 * @Description TODO(realize the rest interface to access by httpPost)
 * @param url
 * @throws Exception
 * @return int (return StatusCode,If zero error said)
 */
public static int httpPost(String url) throws Exception {

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    try {
        CloseableHttpResponse res = httpClient.execute(httpPost);
        try {
            return res.getStatusLine().getStatusCode();
        } finally {
            res.close();
        }
    } catch (ParseException e) {
        LOGGER.error("HttpClient throw ParseException:" + url, e);
    } catch (IOException e) {
        LOGGER.error("HttpClient throw IOException:" + url, e);
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            LOGGER.error("HttpClient Close throw IOException", e);
        }
    }

    return 0;

}

From source file:com.srotya.tau.ui.Utils.java

public static boolean validateStatus(CloseableHttpResponse response) {
    return response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300;
}

From source file:com.networknt.light.server.handler.loader.MenuLoader.java

private static void loadMenuFile(File file) {
    Scanner scan = null;/*from  ww  w .ja  v  a  2s.  co  m*/
    try {
        scan = new Scanner(file, Loader.encoding);
        // the content is only the data portion. convert to map
        String content = scan.useDelimiter("\\Z").next();
        HttpPost httpPost = new HttpPost("http://injector:8080/api/rs");
        StringEntity input = new StringEntity(content);
        input.setContentType("application/json");
        httpPost.setEntity(input);
        CloseableHttpResponse response = httpclient.execute(httpPost);

        try {
            System.out.println(response.getStatusLine());
            HttpEntity entity = response.getEntity();
            BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
            String json = "";
            String line = "";
            while ((line = rd.readLine()) != null) {
                json = json + line;
            }
            System.out.println("json = " + json);
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        if (scan != null)
            scan.close();
    }
}

From source file:org.openo.nfvo.monitor.umc.monitor.common.HttpClientUtil.java

/**
 * @Title httpDelete/*from   w w  w.  j ava 2 s  .  co m*/
 * @Description TODO(realize the rest interface to access by httpDelete)
 * @param url
 * @return
 * @throws Exception
 * @return int (return StatusCode,If zero error said)
 */
public static int httpDelete(String url) throws Exception {

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpDelete httpDelete = new HttpDelete(url);
    try {
        CloseableHttpResponse res = httpClient.execute(httpDelete);
        try {
            return res.getStatusLine().getStatusCode();
        } finally {
            res.close();
        }
    } catch (ParseException e) {
        LOGGER.error("HttpClient throw ParseException:" + url, e);
    } catch (IOException e) {
        LOGGER.error("HttpClient throw IOException:" + url, e);
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            LOGGER.error("HttpClient Close throw IOException", e);
        }
    }

    return 0;

}

From source file:com.google.gct.stats.GoogleUsageTracker.java

private static void sendPing(@NotNull final List<? extends NameValuePair> postData) {
    ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
        public void run() {
            CloseableHttpClient client = HttpClientBuilder.create().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) {
                    LOG.debug("Non 200 status code : " + status.getStatusCode() + " - "
                            + status.getReasonPhrase());
                }//from   w w w  . j a  v a2s  .c o m
            } catch (IOException ex) {
                LOG.debug("IOException during Analytics Ping", new Object[] { ex.getMessage() });
            } finally {
                HttpClientUtils.closeQuietly(client);
            }

        }
    });
}

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

private static void assertIsJsonInfoResponse(CloseableHttpResponse response) throws IOException {
    //status should be 200 OK
    assertThat(response.getStatusLine().getStatusCode(), is(200));

    //response body should not be null
    String bodyAsString = EntityUtils.toString(response.getEntity());
    assertThat(bodyAsString, notNullValue());

    //check content-type of response is json
    String contentMimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();
    assertThat(contentMimeType, equalTo(ContentType.APPLICATION_JSON.getMimeType()));
}

From source file:de.intevation.irix.PrintClient.java

/** Obtains a Report from mapfish-print service.
 *
 * @param printUrl The url to send the request to.
 * @param json The json spec for the print request.
 * @param timeout the timeout for the httpconnection.
 *
 * @return byte[] with the report./*from   w w w .j av  a 2s . c om*/
 *
 * @throws IOException if communication with print service failed.
 * @throws PrintException if the print job failed.
 */
public static byte[] getReport(String printUrl, String json, int timeout) throws IOException, PrintException {

    RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).build();

    CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();

    HttpEntity entity = new StringEntity(json,
            ContentType.create("application/json", Charset.forName("UTF-8")));

    HttpPost post = new HttpPost(printUrl);
    post.setEntity(entity);
    CloseableHttpResponse resp = client.execute(post);

    StatusLine status = resp.getStatusLine();

    byte[] retval = null;
    try {
        HttpEntity respEnt = resp.getEntity();
        InputStream in = respEnt.getContent();
        if (in != null) {
            try {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buf = new byte[BYTE_ARRAY_SIZE];
                int r;
                while ((r = in.read(buf)) >= 0) {
                    out.write(buf, 0, r);
                }
                retval = out.toByteArray();
            } finally {
                in.close();
                EntityUtils.consume(respEnt);
            }
        }
    } finally {
        resp.close();
    }

    if (status.getStatusCode() < HttpURLConnection.HTTP_OK
            || status.getStatusCode() >= HttpURLConnection.HTTP_MULT_CHOICE) {
        if (retval != null) {
            throw new PrintException(new String(retval));
        } else {
            throw new PrintException("Communication with print service '" + printUrl + "' failed."
                    + "\nNo response from print service.");
        }
    }
    return retval;
}

From source file:com.zhch.example.commons.http.v4_5.ClientExecuteProxy.java

public static void proxyExample() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//from   www  .  j  a v a2s.c o m
        HttpHost proxy = new HttpHost("24.157.37.61", 8080, "http");

        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpGet request = new HttpGet("http://www.ip.cn");
        request.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1");

        request.setConfig(config);

        System.out.println(
                "Executing request " + request.getRequestLine() + " to " + request.getURI() + " via " + proxy);

        CloseableHttpResponse response = httpclient.execute(request);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity(), "utf8"));
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}