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:com.dtstack.jlogstash.distributed.http.cilent.HttpClient.java

public static String post(String url, Map<String, Object> bodyData) {
    String responseBody = null;/*from w w  w .  java 2 s .co m*/
    CloseableHttpClient httpClient = null;
    try {
        httpClient = getHttpClient();
        HttpPost httPost = new HttpPost(url);
        if (SetTimeOut) {
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SocketTimeout)
                    .setConnectTimeout(ConnectTimeout).build();//
            httPost.setConfig(requestConfig);
        }
        if (bodyData != null && bodyData.size() > 0) {
            httPost.setEntity(new StringEntity(objectMapper.writeValueAsString(bodyData)));
        }
        //?
        CloseableHttpResponse response = httpClient.execute(httPost);
        int status = response.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            //FIXME ?header?
            responseBody = EntityUtils.toString(entity, Charsets.UTF_8);
        } else {
            logger.error("url:" + url + "--->http return status error:" + status);
        }
    } catch (Exception e) {
        logger.error("url:" + url + "--->http request error", e);
    } finally {
        try {
            if (httpClient != null)
                httpClient.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error(ExceptionUtil.getErrorMessage(e));
        }
    }
    return responseBody;
}

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./*w  w  w .  j a  v  a2 s. c  o m*/
 *
 * @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:eu.citadel.converter.io.index.CitadelIndexUtil.java

/**
 * Get the list of city allowed by citadel index
 * @param url The url that host the city list
 * @return List of allowed city sorted by name
 * @throws ConverterException// w  ww.j  a va 2 s  .co m
 */
public static List<CitadelCityInfo> getCitadelCityInfo(String url) throws ConverterException {
    try {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost request = new HttpPost(url);
        CloseableHttpResponse response = httpclient.execute(request);
        String jsonResponse = EntityUtils.toString(response.getEntity());
        Gson gson = new GsonBuilder().create();
        if (jsonResponse.length() < 11) {
            log.error("Invalid response from server: " + jsonResponse + ".");
            throw new ConverterException("Invalid response from server: " + jsonResponse + ".");
        }
        jsonResponse = jsonResponse.substring(10, jsonResponse.length() - 1);
        List<CitadelCityInfo> infos = gson.fromJson(jsonResponse, new TypeToken<List<CitadelCityInfo>>() {
        }.getType());
        Collections.sort(infos);
        return infos;
    } catch (ParseException | IOException e) {
        log.error(e.getMessage());
        throw new ConverterException(e.getMessage());
    }
}

From source file:com.microsoft.azure.hdinsight.common.StreamUtil.java

public static HttpResponse getResultFromHttpResponse(CloseableHttpResponse response) throws IOException {
    int code = response.getStatusLine().getStatusCode();
    String reason = response.getStatusLine().getReasonPhrase();
    HttpEntity entity = response.getEntity();
    try (InputStream inputStream = entity.getContent()) {
        String response_content = getResultFromInputStream(inputStream);
        return new HttpResponse(code, response_content, new HashMap<String, List<String>>(), reason);
    }/*from w w  w . j a va  2 s  . c  o m*/
}

From source file:org.openo.nfvo.emsdriver.northbound.client.HttpClientUtil.java

public static String doGet(String url, String charset) {
    CloseableHttpClient httpClient = null;
    HttpGet httpGet = null;/*from   ww w  .  j av  a 2 s. c  o  m*/
    String result = null;
    try {
        httpClient = HttpClientFactory.getSSLClientFactory();
        httpGet = new HttpGet(url);

        CloseableHttpResponse response = httpClient.execute(httpGet);

        try {
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception e) {
            log.error("", e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
    } catch (Exception e) {
        log.error("doGet is fail ", e);
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
            }
        }
    }
    return result;
}

From source file:org.openo.nfvo.emsdriver.northbound.client.HttpClientUtil.java

public static String doDelete(String url, String charset) {
    CloseableHttpClient httpClient = null;
    HttpDelete httpDelete = null;//  ww w.ja  v a2  s  .co  m
    String result = null;
    try {
        httpClient = HttpClientFactory.getSSLClientFactory();
        httpDelete = new HttpDelete(url);

        CloseableHttpResponse response = httpClient.execute(httpDelete);

        try {
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception e) {
            log.error("", e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
    } catch (Exception e) {
        log.error("doDelete is fail ", e);
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
            }
        }
    }
    return result;
}

From source file:org.openo.nfvo.emsdriver.northbound.client.HttpClientUtil.java

public static String doPost(String url, String json, String charset) {
    CloseableHttpClient httpClient = null;
    HttpPost httpPost = null;//from   w ww .j  ava2  s . co  m
    String result = null;
    try {
        httpClient = HttpClientFactory.getSSLClientFactory();
        httpPost = new HttpPost(url);
        if (null != json) {
            StringEntity s = new StringEntity(json);
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json"); // set contentType
            httpPost.setEntity(s);
        }
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception e) {
            log.error("httpClient.execute(httpPost) is fail", e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
    } catch (Exception e) {
        log.error("doPost is fail ", e);
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
            }
        }

    }
    return result;
}

From source file:org.dbrane.cloud.util.httpclient.HttpClientHelper.java

/**
 * ?Http//  ww w . j  a v  a  2  s . co  m
 * 
 * @param request
 * @return
 */
private static String getResult(HttpRequestBase request) {
    CloseableHttpClient httpClient = getHttpClient();
    try {
        CloseableHttpResponse response = httpClient.execute(request);
        response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity);
            response.close();
            if (200 == response.getStatusLine().getStatusCode()) {
                return result;
            } else {
                throw new BaseException(ErrorType.Httpclient, result);
            }
        }
        return EMPTY_STR;
    } catch (Exception e) {
        logger.debug(ErrorType.Httpclient.toString(), e);
        throw new BaseException(ErrorType.Httpclient, e);
    } finally {

    }

}

From source file:com.lifetime.util.TimeOffUtil.java

private static List<RepliconTimeOff> getTimeOffInfo(int page, int pageSize) throws IOException, ParseException {

    String url = "https://na5.replicon.com/liferay/services/" + "TimeOffListService1.svc/GetData";

    CloseableHttpClient httpClient = HttpClients.createDefault();

    CredentialsProvider provider = new BasicCredentialsProvider();

    UsernamePasswordCredentials credential = new UsernamePasswordCredentials(COMPANY_NAME + '\\' + USERNAME,
            PASSWORD);//from w w w.j a va 2  s  .c o  m

    provider.setCredentials(AuthScope.ANY, credential);

    HttpClientContext localContext = HttpClientContext.create();

    localContext.setCredentialsProvider(provider);

    HttpPost httpRequest = new HttpPost(url);

    HttpEntity requestEntity = getTimeoffRequestEntity(page, pageSize);

    if (requestEntity != null) {
        httpRequest.setHeader("Content-type", "application/json");
        httpRequest.setEntity(requestEntity);
    }

    CloseableHttpResponse response = httpClient.execute(httpRequest, localContext);

    HttpEntity entity = response.getEntity();

    return createTimeOffList(EntityUtils.toString(entity));
}

From source file:org.knoxcraft.http.client.ClientMultipartFormPost.java

public static void upload(String url, String playerName, File jsonfile, File sourcefile)
        throws ClientProtocolException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*w  ww . j a va  2 s  .c  o m*/
        HttpPost httppost = new HttpPost(url);

        FileBody json = new FileBody(jsonfile);
        FileBody source = new FileBody(sourcefile);
        String jsontext = readFromFile(jsonfile);

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("playerName", new StringBody(playerName, ContentType.TEXT_PLAIN))
                .addPart("jsonfile", json).addPart("sourcefile", source)
                .addPart("language", new StringBody("java", ContentType.TEXT_PLAIN))
                .addPart("jsontext", new StringBody(jsontext, ContentType.TEXT_PLAIN)).addPart("sourcetext",
                        new StringBody("public class Foo {\n  int x=5\n}", ContentType.TEXT_PLAIN))
                .build();

        httppost.setEntity(reqEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            //System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                //System.out.println("Response content length: " + resEntity.getContentLength());
                Scanner sc = new Scanner(resEntity.getContent());
                while (sc.hasNext()) {
                    System.out.println(sc.nextLine());
                }
                sc.close();
                EntityUtils.consume(resEntity);
            }
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}