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

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

Introduction

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

Prototype

HttpEntity getEntity();

Source Link

Usage

From source file:eionet.gdem.utils.HttpUtils.java

/**
 * Downloads remote file/* ww w . j a v  a2s  . c o  m*/
 * @param url URL
 * @return Downloaded file
 * @throws DCMException If an error occurs.
 * @throws IOException If an error occurs.
 */
public static byte[] downloadRemoteFile(String url) throws DCMException, IOException {
    byte[] responseBody = null;
    CloseableHttpClient client = HttpClients.createDefault();

    // Create a method instance.
    HttpGet method = new HttpGet(url);
    // Execute the method.
    CloseableHttpResponse response = null;
    try {
        response = client.execute(method);
        HttpEntity entity = response.getEntity();
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode != HttpStatus.SC_OK) {
            LOGGER.error("Method failed: " + response.getStatusLine().getReasonPhrase());
            throw new DCMException(BusinessConstants.EXCEPTION_SCHEMAOPEN_ERROR,
                    response.getStatusLine().getReasonPhrase());
        }

        // Read the response body.
        InputStream instream = entity.getContent();
        responseBody = IOUtils.toByteArray(instream);

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        // System.out.println(new String(responseBody));
        /*catch (HttpException e) {
        LOGGER.error("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
        throw e;*/
    } catch (IOException e) {
        LOGGER.error("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        throw e;
    } finally {
        // Release the connection.
        response.close();
        method.releaseConnection();
        client.close();
    }
    return responseBody;
}

From source file:com.ibm.streamsx.topology.internal.streaminganalytics.RestUtils.java

public static JsonObject getGsonResponse(CloseableHttpClient httpClient, HttpRequestBase request)
        throws IOException, ClientProtocolException {
    request.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType());

    CloseableHttpResponse response = httpClient.execute(request);
    JsonObject jsonResponse;//w ww  .  j a  v a2s .c  o m
    try {
        HttpEntity entity = response.getEntity();
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            final String errorInfo;
            if (entity != null)
                errorInfo = " -- " + EntityUtils.toString(entity);
            else
                errorInfo = "";
            throw new IllegalStateException(
                    "Unexpected HTTP resource from service:" + response.getStatusLine().getStatusCode() + ":"
                            + response.getStatusLine().getReasonPhrase() + errorInfo);
        }

        if (entity == null)
            throw new IllegalStateException("No HTTP resource from service");

        Reader r = new InputStreamReader(entity.getContent());
        jsonResponse = new Gson().fromJson(r, JsonObject.class);
        EntityUtils.consume(entity);
    } finally {
        response.close();
    }
    return jsonResponse;
}

From source file:eu.citadel.converter.io.index.CitadelIndexUtil.java

/**
 * Index an uploaded file/*from w  w  w  .  j a  v  a2 s.  com*/
 * @param config Index publish configuration
 * @param datasetFile File name of file stored in the dataset
 * @return The response string
 * @throws ClientProtocolException
 * @throws IOException
 */
private static String saveToIndex(CitadelIndexConfig config, String datasetFile)
        throws ClientProtocolException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost request = new HttpPost(config.getSaveIndexUrl());

    ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    postParameters.add(new BasicNameValuePair(REQUEST_PARAM_DATASET_INFO, generateJson(config, datasetFile)));
    request.setEntity(new UrlEncodedFormEntity(postParameters));

    CloseableHttpResponse response = httpclient.execute(request);
    return EntityUtils.toString(response.getEntity());

}

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

public static void proxyExample() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from   ww w .ja  v  a  2 s.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();
    }
}

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  . java 2s .  c  o  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:com.football.site.getdata.ScoreWebService.java

private static String GetHttpClientResponse(String url) {
    String responseText = "";
    try {//from w w  w .  ja  v  a2s. c om
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            httpGet.addHeader("X-Auth-Token", Constants.XAuthToken);
            httpGet.addHeader("Content-type", "application/json");
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            responseText = EntityUtils.toString(httpResponse.getEntity(), "ISO-8859-1");
            //logger.info(String.format("%s - %s", url, responseText));
        }
    } catch (IOException | ParseException e) {
        HelperUtil.AddErrorLog(logger, e);
        HelperUtil.AddErrorLogWithString(logger, url);
    }
    return responseText;
}

From source file:com.oakhole.voa.utils.HttpClientUtils.java

/**
 * ???map// w  w w.ja  v  a 2s .c om
 *
 * @param uri
 * @return
 */
public static HttpEntity get(String uri) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(uri);
    try {
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        return httpResponse.getEntity();
    } catch (IOException e) {
        logger.error(":{}", e.getMessage());
    }
    return null;
}

From source file:org.esigate.http.HttpResponseUtils.java

public static ContentType getContentType(CloseableHttpResponse response) {
    HttpEntity entity = response.getEntity();
    if (entity == null) {
        return null;
    }//from  ww  w . ja  va2s.  c o  m
    return ContentType.get(entity);
}

From source file:com.twinsoft.convertigo.engine.util.HttpUtils.java

public static JSONObject requestToJSON(CloseableHttpClient httpClient, HttpRequestBase request)
        throws ClientProtocolException, IOException, UnsupportedOperationException, JSONException {
    CloseableHttpResponse response = httpClient.execute(request);
    HttpEntity responseEntity = response.getEntity();
    ContentTypeDecoder contentType = new ContentTypeDecoder(
            responseEntity == null || responseEntity.getContentType() == null ? ""
                    : responseEntity.getContentType().getValue());
    JSONObject json = new JSONObject(
            IOUtils.toString(responseEntity.getContent(), contentType.charset("UTF-8")));
    return json;/*from  www.  j a  v  a 2s.  co m*/
}

From source file:org.jboss.pnc.auth.client.SimpleOAuthConnect.java

private static String[] connect(String url, Map<String, String> urlParams)
        throws ClientProtocolException, IOException {

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);

    // add header
    httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

    List<BasicNameValuePair> urlParameters = new ArrayList<BasicNameValuePair>();
    for (String key : urlParams.keySet()) {
        urlParameters.add(new BasicNameValuePair(key, urlParams.get(key)));
    }/* w  w w.j  a va2 s .  com*/
    httpPost.setEntity(new UrlEncodedFormEntity(urlParameters));
    CloseableHttpResponse response = httpclient.execute(httpPost);

    String refreshToken = "";
    String accessToken = "";
    try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        String line = "";
        while ((line = rd.readLine()) != null) {
            if (line.contains("refresh_token")) {
                String[] respContent = line.split(",");
                for (int i = 0; i < respContent.length; i++) {
                    String split = respContent[i];
                    if (split.contains("refresh_token")) {
                        refreshToken = split.split(":")[1].substring(1, split.split(":")[1].length() - 1);
                    }
                    if (split.contains("access_token")) {
                        accessToken = split.split(":")[1].substring(1, split.split(":")[1].length() - 1);
                    }
                }
            }
        }

    } finally {
        response.close();
    }
    return new String[] { accessToken, refreshToken };

}