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:org.geosdi.geoplatform.connector.server.request.PostConnectorRequest.java

@Override
public String getResponseAsString() throws Exception {
    String content;/*from  w  w  w  .  j  av  a 2  s. c om*/

    HttpPost httpPost = this.getPostMethod();
    CloseableHttpResponse httpResponse = super.securityConnector.secure(this, httpPost);
    HttpEntity responseEntity = httpResponse.getEntity();

    if (responseEntity != null) {
        InputStream is = responseEntity.getContent();
        content = CharStreams.toString(new InputStreamReader(is, UTF_8));
        EntityUtils.consume(responseEntity);
    } else {
        throw new IllegalStateException("Connector Server Error: Connection problem");
    }
    return content;
}

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

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

        Gson gson = new Gson();

        //prepare http get
        SalaBean sala = (SalaBean) request.getSession().getAttribute("sala");
        String login_tmst = (String) request.getSession().getAttribute("login_tmst");
        String authToken = String.valueOf(request.getSession().getAttribute("token"));

        URIBuilder builder = new URIBuilder();
        builder.setScheme("http").setHost("25.136.78.82").setPort(8080)
                .setPath("/mensajes/sala/" + sala.getId());
        builder.setParameter("fecha_desde", login_tmst);

        HttpGet getRequest = new HttpGet();
        getRequest.setURI(builder.build());
        getRequest.addHeader("Authorization", "BEARER " + authToken);
        getRequest.addHeader("accept", "application/json; charset=ISO-8859-1");

        CloseableHttpResponse getResponse = httpClient.execute(getRequest);
        HttpEntity responseEntity = getResponse.getEntity();
        StatusLine responseStatus = getResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException(restResp);
        }/* w w w  . ja  v  a 2  s  . c  om*/

        //parse message data from response
        Type listType = new TypeToken<LinkedList<MensajeBean>>() {
        }.getType();
        List<MensajeBean> mensajes = gson.fromJson(restResp, listType);

        if (!mensajes.isEmpty()) {
            request.getSession().setAttribute("ultimo_mensaje",
                    mensajes.get(mensajes.size() - 1).getId_mensaje());
        }

        request.setAttribute("mensajes", mensajes);

        return mapping.getForwardByName("success");

    } catch (IOException | URISyntaxException | RuntimeException e) {
        request.setAttribute("message", "Error al intentar mostrar mensajes: " + e.getMessage());
        response.setStatus(400);
        return mapping.getForwardByName("error");
    }
}

From source file:org.apache.metamodel.neo4j.Neo4jRequestWrapper.java

public String executeRestRequest(HttpRequestBase httpRequest, String username, String password) {
    if ((username != null) && (password != null)) {
        String base64credentials = BaseEncoding.base64()
                .encode((username + ":" + password).getBytes(StandardCharsets.UTF_8));
        httpRequest.addHeader("Authorization", "Basic " + base64credentials);
    }//from   w  w w .  java  2  s .c  om

    try {
        CloseableHttpResponse response = _httpClient.execute(_httpHost, httpRequest);
        if (response.getEntity() != null) {
            return EntityUtils.toString(response.getEntity());
        }
        return null;
    } catch (ClientProtocolException e) {
        logger.error("An error occured while executing " + httpRequest, e);
        throw new IllegalStateException(e);
    } catch (IOException e) {
        logger.error("An error occured while executing " + httpRequest, e);
        throw new IllegalStateException(e);
    }
}

From source file:org.wildfly.swarm.topology.consul.AdvertisingTestBase.java

protected Map<?, ?> getDefinedServicesAsMap() throws IOException {
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.build();

    HttpUriRequest request = new HttpGet(servicesUrl);
    CloseableHttpResponse response = client.execute(request);

    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
    String content = EntityUtils.toString(response.getEntity());
    return mapper.readValue(content, Map.class);
}

From source file:kr.riotapi.core.ApiDomain.java

public String execute(ApiCall call) throws IOException, StatusCodeException {
    HttpGet get = new HttpGet(call.toUrlString());
    String body = null;/*from  w  ww . java2 s  .  com*/
    int statusCode = 0;
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        CloseableHttpResponse response = client.execute(get);
        statusCode = response.getStatusLine().getStatusCode();
        body = EntityUtils.toString(response.getEntity());
        response.close();
    } catch (IOException ex) {
        throw new IOException("There was a problem receiving or processing a server response", ex);
    }
    if (statusCode != HttpStatus.SC_OK)
        throw new StatusCodeException("status code was not 200", statusCode);
    return body;
}

From source file:Onlinedata.MainSendRequest.java

public void downloadData(String filename) {
    downloadurl = baseurl + filename;// w  w w .  ja v  a  2  s . c om
    try {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(downloadurl);
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            response = httpclient.execute(httpget);
            HttpEntity serverEntity = response.getEntity();
            if (serverEntity != null) {
                System.out.println("Found file at adress: " + downloadurl);
                long len = serverEntity.getContentLength();
                System.out.println("Length is " + len);
                download = EntityUtils.toString(serverEntity);
                System.out.println(download);
            }
        } catch (IOException | ParseException ex) {
            Logger.getLogger(MainSendRequest.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            response.close();
        }
        httpclient.close();
    } catch (IOException ex) {
        Logger.getLogger(MainSendRequest.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:au.org.ncallister.goodbudget.tools.coms.GoodBudgetSession.java

public String get(String path, List<NameValuePair> parameters) throws URISyntaxException, IOException {
    URIBuilder builder = new URIBuilder(BASE_URI);
    builder.setPath(path);/*from  w  ww . ja v a2  s .c om*/
    builder.setParameters(parameters);
    HttpGet get = new HttpGet(builder.build());

    CloseableHttpResponse response = client.execute(get, sessionContext);
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        return reader.lines().collect(Collectors.joining("\n"));
    } finally {
        response.close();
    }
}

From source file:actions.ScanFileAction.java

String getStringFromClosableHttpResponse(CloseableHttpResponse response) {
    try {/*www.j a v  a  2  s . c o m*/
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuilder result = new StringBuilder();
        String line = "";

        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        return result.toString();
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    return "";
}

From source file:javaeetutorial.web.websocketbot.BotBean.java

public String get(String msg, String uri) {
    msg = msg.toLowerCase().replaceAll("\\?", "");
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//w  w  w  .ja v  a  2s  . c  om
        HttpGet httpget = new HttpGet(uri + msg);
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();
            System.out.println(response.getStatusLine());
            if (entity != null) {
                String jsonresult = EntityUtils.toString(entity);
                System.out.println("Response content:" + jsonresult);
                return jsonresult;
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    } catch (Exception e) {
        // TODO: handle exception
    } finally {
        try {
            httpclient.close();
        } catch (Exception e2) {
            // TODO: handle exception
        }
    }
    return null;
}

From source file:io.crate.integrationtests.RestSQLActionIntegrationTest.java

@Test
public void testWithoutBody() throws IOException {
    CloseableHttpResponse response = post(null);
    assertEquals(400, response.getStatusLine().getStatusCode());
    String bodyAsString = EntityUtils.toString(response.getEntity());
    assertThat(bodyAsString, startsWith("{\"error\":{\"message\":\"SQLActionException[missing request body]\","
            + "\"code\":4000},\"error_trace\":\"SQLActionException:"));
}