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.owasp.benchmark.tools.BenchmarkCrawler.java

public static void sendPost(CloseableHttpClient httpclient, HttpPost post) throws Exception {
    CloseableHttpResponse response = httpclient.execute(post);
    System.out.println("POST " + post.getURI());
    try {//from  www . j  av a2 s.  co m
        HttpEntity entity = response.getEntity();
        System.out.println("--> (" + response.getStatusLine().getStatusCode() + ") ");
        EntityUtils.consume(entity);
    } finally {
        response.close();
    }
}

From source file:fridgegameinstaller.MCJsonConf.java

public static void getJson(String path, int mb) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet("http://api.fridgegame.com/mcconf/Fridgegame.json");

    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    try {/*from   w  w  w. j av  a 2  s . c  om*/
        System.out.println(httpGet.toString());
        System.out.println(response1.getStatusLine());
        BufferedReader br = new BufferedReader(new InputStreamReader(response1.getEntity().getContent()));
        String a;
        String output = "";
        while ((a = br.readLine()) != null) {
            output += a + "\n";
        }
        System.out.println(output);
        try {

            JSONObject json = new JSONObject(output);
            String mcArgs = json.getString("minecraftArguments");
            String regex = "(-Xmx[^ ]*)";
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(mcArgs);
            String newArgs = m.replaceAll("-Xmx" + mb + "M");
            json.put("minecraftArguments", newArgs);
            FileWriter file = new FileWriter(path);

            try {
                file.write(json.toString());

            } catch (IOException e) {
                e.printStackTrace();

            } finally {
                file.flush();
                file.close();
            }

        } catch (JSONException e) {

        }
    } finally {
        response1.close();
    }

}

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

/**
 * ?Get,?//from   w ww  .j  ava2s.c o m
 *
 * @param uri
 * @param map
 * @return
 */
public static HttpEntity get(String uri, Map<String, String> map) {

    CloseableHttpClient httpClient = HttpClients.createDefault();
    List<NameValuePair> list = Lists.newArrayList();
    for (String key : map.keySet()) {
        list.add(new BasicNameValuePair(key, map.get(key)));
    }

    String param = URLEncodedUtils.format(list, CHARSET);
    String url = uri + "?" + param;
    HttpGet httpGet = new HttpGet(url);
    try {
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        httpResponse.close();
        return httpResponse.getEntity();
    } catch (IOException e) {
        logger.error(":{}", e.getMessage());
    }
    return null;
}

From source file:org.eclipse.dirigible.cli.apis.ImportProjectAPI.java

private static void executeRequest(CloseableHttpClient httpClient, HttpPost postRequest)
        throws IOException, ClientProtocolException {
    try {// w ww  .j a  va  2 s . c om
        CloseableHttpResponse response = httpClient.execute(postRequest);
        try {
            logger.log(Level.INFO, "----------------------------------------");
            logger.log(Level.INFO, response.getStatusLine().toString());
            HttpEntity resultEntity = response.getEntity();
            if (resultEntity != null) {
                logger.log(Level.INFO, "Response content length: " + resultEntity.getContentLength());
            }
            EntityUtils.consume(resultEntity);
        } finally {
            response.close();
        }
    } finally {
        httpClient.close();
    }
}

From source file:org.wso2.carbon.ml.MLTestUtils.java

public static String getJsonArrayAsString(CloseableHttpResponse response) throws IOException, JSONException {
    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(response.getEntity().getContent()));
    JSONArray responseJson = new JSONArray(bufferedReader.readLine());
    bufferedReader.close();//  www. ja  v  a 2 s.com
    response.close();

    return responseJson.toString();
}

From source file:eu.ebbitsproject.peoplemanager.utils.HttpUtils.java

public static String findPerson(String errorType, String location) {

    CloseableHttpClient httpClient = HttpClients.createDefault();

    String url = PropertiesUtils.getProperty("uiapp.address");

    HttpPost httpPost = new HttpPost(url);

    List<NameValuePair> nvps = new ArrayList<>();
    nvps.add(new BasicNameValuePair("action", "find-persons"));
    String properties = "demo-e1:competence=" + errorType + ",demo-e1:area-responsibility=" + location;
    String pmProperties = "available=true";
    nvps.add(new BasicNameValuePair("properties", properties));
    nvps.add(new BasicNameValuePair("pmProperties", pmProperties));

    try {// w w  w .  j a  v  a  2 s . c  o m
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(HttpUtils.class.getName()).log(Level.SEVERE, null, ex);
    }

    CloseableHttpResponse response = null;
    String personJSON = null;
    try {
        response = httpClient.execute(httpPost);
        personJSON = EntityUtils.toString(response.getEntity());
        System.out.println("######## PersonJSON: " + personJSON);
    } catch (IOException e) {
        Logger.getLogger(HttpUtils.class.getName()).log(Level.SEVERE, null, e);
    } finally {
        try {
            response.close();
        } catch (IOException e) {
            Logger.getLogger(HttpUtils.class.getName()).log(Level.SEVERE, null, e);
        }
    }

    if (personJSON != null) {
        JSONArray persons = (JSONArray) JSONValue.parse(personJSON);
        Iterator<JSONObject> i = persons.iterator();
        if (i.hasNext()) {
            JSONObject o = i.next();
            return o.get("id").toString();
        }
    }

    return personJSON;
}

From source file:eu.ebbitsproject.peoplemanager.utils.HttpUtils.java

public static void postData(String url, String action, String errorType, String objectId, String personId,
        String eventId) {//from www . j  a  v  a  2  s.  c o  m
    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost(url);
    List<NameValuePair> nvps = new ArrayList<>();
    nvps.add(new BasicNameValuePair("action", action));
    nvps.add(new BasicNameValuePair("personId", personId));
    nvps.add(new BasicNameValuePair("errorType", errorType));
    nvps.add(new BasicNameValuePair("objectId", objectId));
    nvps.add(new BasicNameValuePair("eventId", eventId));

    System.out.println("action = " + action);
    System.out.println("personId = " + personId);
    System.out.println("errorType = " + errorType);
    System.out.println("objectId = " + objectId);
    System.out.println("eventId = " + eventId);

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(HttpUtils.class.getName()).log(Level.SEVERE, null, ex);
    }

    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(httpPost);
        System.out.println(response.getStatusLine());
        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);
    } catch (IOException e) {
        Logger.getLogger(HttpUtils.class.getName()).log(Level.SEVERE, null, e);
    } finally {
        try {
            response.close();
        } catch (IOException e) {
            Logger.getLogger(HttpUtils.class.getName()).log(Level.SEVERE, null, e);
        }
    }
}

From source file:com.meli.client.controller.AppController.java

private static void doApiCalls(String query, String countryCode) {
        List<Item> items = new ArrayList<Item>();
        Random r = new Random();

        Meli meliOb = new Meli(2072832875526076L, "1VZEFfhbSCy3vDDrh0Dp96NkfgNOWPGq");
        try {/*from   w  ww.j a  va2  s . c  o  m*/

            FluentStringsMap params = new FluentStringsMap();
            params.add("q", query);

            String path = countryCode.isEmpty() ? "/sites/MLA/search/" : "/sites/" + countryCode + "/search";
            Response response = meliOb.get(path, params);

            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(response.getResponseBody());
            JsonNode resultNode = rootNode.findPath("results");

            if (resultNode.size() > 0) {
                JsonNode currNode = null;
                JsonNode dupNode = null;
                boolean dupNodeVal = false;

                CloseableHttpClient httpClient = HttpClientBuilder.create().build();

                Item item = null;

                int randomMins;

                String checkDupsUrl = null;

                HttpGet get = null;
                URIBuilder builder = null;
                URI uri = null;

                for (int i = 0; i < resultNode.size(); i++) {
                    currNode = resultNode.get(i);

                    builder = new URIBuilder();
                    builder.setScheme("http").setHost(apiUrl).setPath("/api/proxy/check")
                            .setParameter("host", "test").setParameter("itemID", currNode.get("id").asText());
                    uri = builder.build();

                    get = new HttpGet(uri);
                    get.addHeader("accept", "application/json");

                    CloseableHttpResponse res = httpClient.execute(get);
                    BufferedReader br = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
                    String content = "", line;

                    while ((line = br.readLine()) != null) {
                        content = content + line;
                    }

                    if (!content.isEmpty()) {
                        dupNode = objectMapper.readTree(content);
                        dupNodeVal = Boolean.parseBoolean(dupNode.get("isDuplicate").asText());

                        if (dupNodeVal && !allowDuplicates)
                            continue;

                        item = new Item(query, currNode.get("id").asText(), "", //currNode.get("host").asText(),?? 
                                currNode.get("site_id").asText(), currNode.get("title").asText(),
                                currNode.get("permalink").asText(), currNode.get("category_id").asText(),
                                currNode.get("seller").get("id").asText(), "", //currNode.get("seller").get("name").asText()
                                "", //currNode.get("seller").get("link").asText()
                                "", //currNode.get("seller").get("email").asText()
                                currNode.get("price").asText(), "", //currNode.get("auction_price").asText(),
                                "", //currNode.get("currency_id").asText(),
                                currNode.get("thumbnail").asText());
                        items.add(item);
                    }
                    randomMins = (int) (Math.random() * (maxWaitTime - minWaitTime)) + minWaitTime;
                    Thread.sleep(randomMins);
                }

                if (!items.isEmpty()) {
                    HttpPost post = new HttpPost(apiUrl + "/proxy/add");
                    StringEntity stringEntity = new StringEntity(objectMapper.writeValueAsString(items));

                    post.setEntity(stringEntity);
                    post.setHeader("Content-type", "application/json");

                    CloseableHttpResponse postResponse = httpClient.execute(post);
                    System.out.println("this is the reponse of the final request: "
                            + postResponse.getStatusLine().getStatusCode());
                }
            }

        } catch (MeliException ex) {
            Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (URISyntaxException ex) {
            Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

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:com.ibm.mobilefirstplatform.serversdk.java.push.PushNotifications.java

protected static void sendResponseToListener(CloseableHttpResponse response,
        PushNotificationsResponseListener listener) throws IOException {
    String responseBody = null;//www  . j a  va  2 s . co  m

    if (response.getEntity() != null) {
        ByteArrayOutputStream outputAsByteArray = new ByteArrayOutputStream();
        response.getEntity().writeTo(outputAsByteArray);

        responseBody = new String(outputAsByteArray.toByteArray());
    }

    Integer statusCode = null;

    if (response.getStatusLine() != null) {
        statusCode = response.getStatusLine().getStatusCode();
    }

    if (statusCode != null && statusCode == HttpStatus.SC_ACCEPTED) {
        listener.onSuccess(statusCode, responseBody);
    } else {
        listener.onFailure(statusCode, responseBody, null);
    }
}