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:cn.org.once.cstack.service.impl.MonitoringServiceImpl.java

@Override
public String getJsonMachineFromCAdvisor() {
    String result = "";
    try {/*from ww w  . j  a va  2  s . c  om*/
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(cAdvisorURL + "/api/v1.3/machine");
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            result = EntityUtils.toString(response.getEntity());
            if (logger.isDebugEnabled()) {
                logger.debug(result);
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        logger.error("" + e);
    }
    return result;
}

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

private String adaptBody(CloseableHttpResponse apacheResponse) throws IOException {
    HttpEntity entity = apacheResponse.getEntity();
    if (entity == null) {
        return "";
    } else {//  ww  w. ja  v a 2 s  . c o  m
        return EntityUtils.toString(entity, UTF_8);
    }
}

From source file:com.microsoft.azure.hdinsight.common.task.LivyTask.java

@Override
public String call() throws Exception {
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider)
            .build();// w  w w. j av  a2 s . c  om
    HttpGet httpGet = new HttpGet(path);
    httpGet.addHeader("Content-Type", "application/json");
    CloseableHttpResponse response = httpclient.execute(httpGet);
    int code = response.getStatusLine().getStatusCode();

    HttpEntity httpEntity = response.getEntity();

    return IOUtils.toString(httpEntity.getContent(), Charset.forName("utf-8"));
}

From source file:org.n52.socialmedia.harvester.storage.InsertObservationToSOS.java

private String executePost(String requestContent) throws IOException {
    HttpPost post = new HttpPost(SOS_URL);
    post.setHeader("Content-Type", "application/soap+xml");
    post.setHeader("Accept", "application/soap+xml");
    post.setEntity(new StringEntity(requestContent));

    LOGGER.debug("Request to send: \n{}", requestContent);

    try (CloseableHttpClient client = HttpClientBuilder.create().build();) {
        CloseableHttpResponse response = client.execute(post);

        if (response.getEntity() != null) {
            String content = EntityUtils.toString(response.getEntity());
            LOGGER.info("response: " + content);
            return content;
        } else {//from w  w w .ja  v a 2  s . c  o  m
            LOGGER.warn("Could not retrieve contents. No entity.");
        }
    } catch (IOException e) {
        LOGGER.warn("Could not retrieve contents of " + post.getURI(), e);
    }

    return null;
}

From source file:com.clonephpscrapper.utility.FetchPageWithProxy.java

public static String fetchPageSourcefromClientGoogleSecond(URI newurl) throws IOException {

    int portNo = generateRandomPort();
    CredentialsProvider credsprovider = new BasicCredentialsProvider();
    credsprovider.setCredentials(new AuthScope("195.154.161.103", portNo),
            new UsernamePasswordCredentials("mongoose", "Fjh30fi"));
    HttpHost proxy = new HttpHost("195.154.161.103", portNo);
    //-----------------------------------------------------------------------
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).build();

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsprovider)
            .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0")
            .setDefaultRequestConfig(requestConfig).setProxy(proxy).build();
    String responsebody = "";
    String responsestatus = null;
    try {//from w  ww. j a  v  a 2s.  com
        HttpGet httpget = new HttpGet(newurl);
        httpget.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        httpget.addHeader("Accept-Encoding", "gzip, deflate");
        httpget.addHeader("Accept-Language", "en-US,en;q=0.5");
        httpget.addHeader("Connection", "keep-alive");

        System.out.println("Response status" + httpget.getRequestLine());
        CloseableHttpResponse resp = httpclient.execute(httpget);
        responsestatus = resp.getStatusLine().toString();
        if (responsestatus.contains("503") || responsestatus.contains("502") || responsestatus.contains("400")
                || responsestatus.contains("401") || responsestatus.contains("402")
                || responsestatus.contains("403") || responsestatus.contains("407")
                || responsestatus.contains("404") || responsestatus.contains("405")
                || responsestatus.contains("SSLHandshakeException") || responsestatus.contains("999")
                || responsestatus.contains("ClientProtocolException")
                || responsestatus.contains("SocketTimeoutException") || responsestatus == null
                || "".equals(responsestatus)) {
            return null;
        } else {
            HttpEntity entity = resp.getEntity();
            System.out.println(resp.getStatusLine());
            if (entity != null) {
                //                    System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    responsebody = new StringBuilder().append(responsebody).append(inputLine).toString();
                }
                // writeResponseFile(responsebody, pagename);
            }
            EntityUtils.consume(entity);
        }
    } catch (IOException | IllegalStateException e) {
        return null;
    } finally {
        httpclient.close();
    }
    return responsebody;
}

From source file:com.navercorp.pinpoint.plugin.httpclient4.CloaeableHttpClientIT.java

@Test
public void test() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*  w  w w  .  j a  v  a 2 s  . c  om*/
        HttpGet httpget = new HttpGet("http://www.naver.com");
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    instream.read();
                } catch (IOException ex) {
                    throw ex;
                } finally {
                    instream.close();
                }
            }
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();

    verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL",
            CloseableHttpClient.class.getMethod("execute", HttpUriRequest.class)));
    verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL",
            PoolingHttpClientConnectionManager.class.getMethod("connect", HttpClientConnection.class,
                    HttpRoute.class, int.class, HttpContext.class),
            annotation("http.internal.display", "www.naver.com:80")));
    verifier.verifyTrace(event("HTTP_CLIENT_4",
            HttpRequestExecutor.class.getMethod("execute", HttpRequest.class, HttpClientConnection.class,
                    HttpContext.class),
            null, null, "www.naver.com", annotation("http.url", "/"), annotation("http.status.code", 200),
            annotation("http.io", anyAnnotationValue())));
    verifier.verifyTraceCount(0);
}

From source file:org.geosdi.geoplatform.connector.server.request.PostConnectorRequest.java

@Override
public InputStream getResponseAsStream() throws Exception {
    HttpPost httpPost = this.getPostMethod();
    CloseableHttpResponse httpResponse = super.securityConnector.secure(this, httpPost);

    HttpEntity responseEntity = httpResponse.getEntity();
    if (responseEntity != null) {
        return responseEntity.getContent();

    } else {//from w  w  w .ja v  a2s .  c om
        throw new IllegalStateException("Connector Server Error: " + "Connection problem");
    }
}

From source file:ar.edu.ubp.das.src.chat.actions.SalasJoinAction.java

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {

        //get user data from session storage
        Gson gson = new Gson();
        Type usuarioType = new TypeToken<LoginTempBean>() {
        }.getType();/*from  w w w . j av a2  s .co  m*/
        String sessUser = String.valueOf(request.getSession().getAttribute("user"));
        LoginTempBean user = gson.fromJson(sessUser, usuarioType);

        //prepare http post
        HttpPost httpPost = new HttpPost("http://25.136.78.82:8080/usuarios-salas/");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("id_usuario", user.getId()));
        params.add(new BasicNameValuePair("id_sala", form.getItem("id_sala")));
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        httpPost.addHeader("Authorization", "BEARER " + request.getSession().getAttribute("token"));
        httpPost.addHeader("accept", "application/json");

        CloseableHttpResponse postResponse = httpClient.execute(httpPost);

        HttpEntity responseEntity = postResponse.getEntity();
        StatusLine responseStatus = postResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException(restResp);
        }

        //get user data from session storage
        String salas = String.valueOf(request.getSession().getAttribute("salas"));
        List<SalaBean> salaList = gson.fromJson(salas, new TypeToken<List<SalaBean>>() {
        }.getType());
        SalaBean actual = salaList.stream().filter(s -> s.getId() == Integer.parseInt(form.getItem("id_sala")))
                .collect(Collectors.toList()).get(0);

        request.getSession().setAttribute("sala", actual);
        request.getSession().setAttribute("ultima_actualizacion", String.valueOf(System.currentTimeMillis()));

        return mapping.getForwardByName("success");

    } catch (IOException | RuntimeException e) {
        request.setAttribute("message", "Error al intentar ingresar a Sala: " + e.getMessage());
        response.setStatus(400);
        return mapping.getForwardByName("failure");
    }
}

From source file:ch.ralscha.extdirectspring_itest.ExceptionFormPostServiceTest.java

@Test
public void testExceptionHandling() throws IOException {

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("extTID", "3"));
    formparams.add(new BasicNameValuePair("extAction", "exceptionFormPostService"));
    formparams.add(new BasicNameValuePair("extMethod", "throwAException"));
    formparams.add(new BasicNameValuePair("extType", "rpc"));
    formparams.add(new BasicNameValuePair("extUpload", "false"));

    UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(formparams, "UTF-8");

    this.post.setEntity(postEntity);

    CloseableHttpResponse response = this.client.execute(this.post);
    HttpEntity entity = response.getEntity();
    assertThat(entity).isNotNull();//from  w  ww  .  j  a v a2  s. c om
    String responseString = EntityUtils.toString(entity);
    ObjectMapper mapper = new ObjectMapper();

    Map<String, Object> rootAsMap = mapper.readValue(responseString, Map.class);
    assertThat(rootAsMap).hasSize(6);
    assertThat(rootAsMap.get("method")).isEqualTo("throwAException");
    assertThat(rootAsMap.get("type")).isEqualTo("exception");
    assertThat(rootAsMap.get("action")).isEqualTo("exceptionFormPostService");
    assertThat(rootAsMap.get("tid")).isEqualTo(3);
    assertThat(rootAsMap.get("message")).isEqualTo("a null pointer");

    @SuppressWarnings("unchecked")
    Map<String, Object> result = (Map<String, Object>) rootAsMap.get("result");
    assertThat(result).hasSize(1);
    assertThat((Boolean) result.get("success")).isFalse();
    IOUtils.closeQuietly(response);
}