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.xwiki.contrib.repository.npm.internal.utils.NpmHttpUtils.java

public static InputStream performGet(URI uri, HttpClientFactory httpClientFactory, HttpContext localContext,
        Header[] headers) throws HttpException {
    HttpGet getMethod = new HttpGet(uri);
    getMethod.setHeaders(headers);/*from   w ww . j  av a  2s .  c o  m*/
    CloseableHttpClient httpClient = httpClientFactory.createClient(null, null);
    CloseableHttpResponse response;
    try {
        if (localContext != null) {
            response = httpClient.execute(getMethod, localContext);
        } else {
            response = httpClient.execute(getMethod);
        }
    } catch (Exception e) {
        throw new HttpException(String.format("Failed to request [%s]", getMethod.getURI()), e);
    }

    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_OK) {
        try {
            return response.getEntity().getContent();
        } catch (IOException e) {
            throw new HttpException(
                    String.format("Failed to parse response body of request [%s]", getMethod.getURI()), e);
        }
    } else {
        throw new HttpException(String.format("Invalid answer [%s] from the server when requesting [%s]",
                response.getStatusLine().getStatusCode(), getMethod.getURI()));
    }
}

From source file:org.wuspba.ctams.ws.ITBandRegistrationController.java

protected static void delete() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("id", TestFixture.INSTANCE.bandRegistration.getId()).build();

    HttpDelete httpDelete = new HttpDelete(uri);

    CloseableHttpResponse response = null;

    try {//w  ww.  ja va 2 s  .co m
        response = httpclient.execute(httpDelete);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }

    ITBandController.delete();
}

From source file:org.wuspba.ctams.ws.ITSoloRegistrationController.java

protected static void delete() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("id", TestFixture.INSTANCE.soloRegistration.getId()).build();

    HttpDelete httpDelete = new HttpDelete(uri);

    CloseableHttpResponse response = null;

    try {/* www.  j a  v  a2  s. co m*/
        response = httpclient.execute(httpDelete);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }

    ITPersonController.delete();
}

From source file:org.wuspba.ctams.ws.ITBandMemberController.java

private static void add(BandMember m) throws Exception {
    CTAMSDocument doc = new CTAMSDocument();
    doc.getPeople().add(m.getPerson());/*  w w w .  java  2  s  . c  o  m*/
    doc.getBandMembers().add(m);
    String xml = XMLUtils.marshal(doc);

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpPost httpPost = new HttpPost(uri);

    StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    CloseableHttpResponse response = null;

    try {
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        doc = IntegrationTestUtils.convertEntity(responseEntity);

        m.setId(doc.getBandMembers().get(0).getId());

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }
}

From source file:com.networknt.light.server.handler.loader.PageLoader.java

/**
 * Get all pages from the server and construct a map in order to compare content
 * to detect changes or not.//  w  w  w .j  a v  a  2 s . co m
 *
 */
private static void getPageMap(String host) {

    Map<String, Object> inputMap = new HashMap<String, Object>();
    inputMap.put("category", "page");
    inputMap.put("name", "getPageMap");
    inputMap.put("readOnly", true);

    CloseableHttpResponse response = null;
    try {
        HttpPost httpPost = new HttpPost(host + "/api/rs");
        httpPost.addHeader("Authorization", "Bearer " + jwt);
        StringEntity input = new StringEntity(
                ServiceLocator.getInstance().getMapper().writeValueAsString(inputMap));
        input.setContentType("application/json");
        httpPost.setEntity(input);
        response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
        String json = "";
        String line = "";
        while ((line = rd.readLine()) != null) {
            json = json + line;
        }
        EntityUtils.consume(entity);
        System.out.println("Got page map from server");
        if (json != null && json.trim().length() > 0) {
            pageMap = ServiceLocator.getInstance().getMapper().readValue(json,
                    new TypeReference<HashMap<String, String>>() {
                    });
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

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

@SuppressWarnings("unchecked")
private static void testAndCheck(String action, String method, Integer total, boolean success)
        throws IOException, JsonParseException, JsonMappingException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    CloseableHttpResponse response = null;
    try {/*from w  w w .jav a 2s. c om*/
        HttpPost post = new HttpPost("http://localhost:9998/controller/router");

        StringEntity postEntity = new StringEntity("{\"action\":\"" + action + "\",\"method\":\"" + method
                + "\",\"data\":[],\"type\":\"rpc\",\"tid\":1}", "UTF-8");
        post.setEntity(postEntity);
        post.setHeader("Content-Type", "application/json; charset=UTF-8");

        response = client.execute(post);
        HttpEntity entity = response.getEntity();
        assertThat(entity).isNotNull();
        String responseString = EntityUtils.toString(entity);

        assertThat(responseString).isNotNull();
        assertThat(responseString).startsWith("[").endsWith("]");

        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> rootAsMap = mapper
                .readValue(responseString.substring(1, responseString.length() - 1), Map.class);
        assertEquals(5, rootAsMap.size());

        assertEquals(method, rootAsMap.get("method"));
        assertEquals("rpc", rootAsMap.get("type"));
        assertEquals(action, rootAsMap.get("action"));
        assertEquals(1, rootAsMap.get("tid"));

        Map<String, Object> result = (Map<String, Object>) rootAsMap.get("result");
        if (total != null) {
            assertEquals(3, result.size());
            assertThat((Integer) result.get("total")).isEqualTo(total);
        } else {
            assertEquals(2, result.size());
        }
        assertThat((Boolean) result.get("success")).isEqualTo(success);

        List<Map<String, Object>> records = (List<Map<String, Object>>) result.get("records");
        assertEquals(2, records.size());

        assertEquals("4cf8e5b8924e23349fb99454", ((Map<String, Object>) records.get(0).get("_id")).get("$oid"));
        assertEquals("4cf8e5b8924e2334a0b99454", ((Map<String, Object>) records.get(1).get("_id")).get("$oid"));
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(client);
    }
}

From source file:com.aws.sampleImage.url.TestHttpGetFlickrAPIProfile.java

private static String callFlickrAPIForEachKeyword(String query) throws IOException, JSONException {
    String apiKey = "ad4f88ecfd53b17f93178e19703fe00d";
    String apiSecret = "96cab0e9f89468d6";

    long httpCallTime = 0L;
    long jsonParseTime = 0L;

    int totalPages = 4;

    int total = 500;
    int perPage = 500;

    int counter = 0;

    int currentCount = 0;

    for (int i = 1; i <= totalPages && currentCount <= total; i++, currentCount = currentCount + perPage) {

        long startHttpCall = System.currentTimeMillis();

        String url = "https://api.flickr.com/services/rest/?method=flickr.photos.search&text=" + query
                + "&extras=url_c,url_m,url_n,license,owner_name&per_page=500&page=" + i
                + "&format=json&api_key=" + apiKey + "&api_secret=" + apiSecret + "&license=4,5,6,7,8";

        System.out.println("URL FORMED --> " + url);

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

        System.out.println("GET Response Status:: " + httpResponse.getStatusLine().getStatusCode());

        long endHttpCall = System.currentTimeMillis();

        httpCallTime = (long) (httpCallTime + (long) (endHttpCall - startHttpCall));

        long startJsonParse = System.currentTimeMillis();

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(httpResponse.getEntity().getContent()));

        String inputLine;/*from ww  w  .j av  a  2  s .c om*/
        StringBuffer response = new StringBuffer();

        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();

        String responseString = response.toString();

        responseString = responseString.replace("jsonFlickrApi(", "");

        int length = responseString.length();

        responseString = responseString.substring(0, length - 1);

        // print result
        System.out.println("After making it a valid JSON --> " + responseString);
        httpClient.close();

        JSONObject json = null;
        try {
            json = new JSONObject(responseString);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //System.out.println("Converted JSON String " + json);

        JSONObject photosObj = json.has("photos") ? json.getJSONObject("photos") : null;
        total = photosObj.has("total") ? (Integer.parseInt(photosObj.getString("total"))) : 0;
        perPage = photosObj.has("perpage") ? (Integer.parseInt(photosObj.getString("perpage"))) : 0;

        System.out.println(" perPage --> " + perPage + " total --> " + total);

        JSONArray photoArr = photosObj.getJSONArray("photo");
        System.out.println("Length of Array --> " + photoArr.length());
        String scrapedImageURL = "";

        for (int itr = 0; itr < photoArr.length(); itr++) {
            JSONObject tempObject = photoArr.getJSONObject(itr);
            scrapedImageURL = tempObject.has("url_c") ? tempObject.getString("url_c")
                    : tempObject.has("url_m") ? tempObject.getString("url_m")
                            : tempObject.has("url_n") ? tempObject.getString("url_n") : "";

            //System.out.println("Scraped Image URL --> " + scrapedImageURL);

            counter++;
        }

        long endJsonParse = System.currentTimeMillis();

        jsonParseTime = (long) (jsonParseTime + (long) (endJsonParse - startJsonParse));

    }

    System.out.println("C O U N T E R -> " + counter);

    System.out.println("HTTP CALL TIME --> " + httpCallTime + " JSON PARSE TIME --> " + jsonParseTime);

    return null;
}

From source file:org.wuspba.ctams.ws.ITVenueController.java

protected static void add() throws Exception {
    CTAMSDocument doc = new CTAMSDocument();
    doc.getVenues().add(TestFixture.INSTANCE.venue);
    String xml = XMLUtils.marshal(doc);

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpPost httpPost = new HttpPost(uri);

    StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    CloseableHttpResponse response = null;

    try {//from   w  w w . jav  a  2 s  . c o  m
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        doc = IntegrationTestUtils.convertEntity(responseEntity);

        TestFixture.INSTANCE.venue.setId(doc.getVenues().get(0).getId());

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }
}

From source file:DeliverWork.java

private static String saveIntoWeed(RemoteFile remoteFile, String projectId)
        throws SQLException, UnsupportedEncodingException {
    String url = "http://59.215.226.174/WebDiskServerDemo/doc?doc_id="
            + URLEncoder.encode(remoteFile.getFileId(), "utf-8");
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;
    String res = "";
    try {//  w w w. ja v  a 2 s  . c  om
        httpClient = HttpClients.createSystem();
        // http(get?)
        HttpGet httpget = new HttpGet(url);
        response = httpClient.execute(httpget);
        HttpEntity result = response.getEntity();
        String fileName = remoteFile.getFileName();
        FileHandleStatus fileHandleStatus = getFileTemplate().saveFileByStream(fileName,
                new ByteArrayInputStream(EntityUtils.toByteArray(result)));
        System.out.println(fileHandleStatus);
        File file = new File();
        if (result != null && result.getContentType() != null && result.getContentType().getValue() != null) {
            file.setContentType(result.getContentType().getValue());
        } else {
            file.setContentType("application/error");
        }
        file.setDataId(Integer.parseInt(projectId));
        file.setName(fileName);
        if (fileName.contains(".bmp") || fileName.contains(".jpg") || fileName.contains(".jpeg")
                || fileName.contains(".png") || fileName.contains(".gif")) {
            file.setType(1);
        } else if (fileName.contains(".doc") || fileName.contains(".docx")) {
            file.setType(2);
        } else if (fileName.contains(".xlsx") || fileName.contains("xls")) {
            file.setType(3);
        } else if (fileName.contains(".pdf")) {
            file.setType(4);
        } else {
            file.setType(5);
        }
        String accessUrl = "/" + fileHandleStatus.getFileId().replaceAll(",", "/").concat("/").concat(fileName);
        file.setUrl(accessUrl);
        file.setSize(fileHandleStatus.getSize());
        file.setPostTime(new java.util.Date());
        file.setStatus(0);
        file.setEnumValue(findFileType(remoteFile.getFileType()));
        file.setResources(1);
        //            JdbcFactory jdbcFactoryChanye=new JdbcFactory("jdbc:mysql://127.0.0.1:3306/fp_guimin?useUnicode=true&characterEncoding=UTF-8","root","111111","com.mysql.jdbc.Driver");
        //            Connection connection = jdbcFactoryChanye.getConnection();
        DatabaseMetaData dmd = connection.getMetaData();
        PreparedStatement ps = connection.prepareStatement(insertFile, new String[] { "ID" });
        ps.setString(1, sdf.format(file.getPostTime()));
        ps.setInt(2, file.getType());
        ps.setString(3, file.getEnumValue());
        ps.setInt(4, file.getDataId());
        ps.setString(5, file.getUrl());
        ps.setString(6, file.getName());
        ps.setString(7, file.getContentType());
        ps.setLong(8, file.getSize());
        ps.setInt(9, file.getStatus());
        ps.setInt(10, file.getResources());
        ps.executeUpdate();
        if (dmd.supportsGetGeneratedKeys()) {
            ResultSet rs = ps.getGeneratedKeys();
            while (rs.next()) {
                System.out.println(rs.getLong(1));
            }
        }
        ps.close();
        res = "success";
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        res = e.getMessage();
    } catch (IOException e) {
        e.printStackTrace();
        res = e.getMessage();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return res;
}

From source file:org.wuspba.ctams.ws.ITHiredJudgeController.java

protected static void add() throws Exception {
    ITJudgeController.add();//from w w  w  .  j a  v a  2  s .  c  o  m

    CTAMSDocument doc = new CTAMSDocument();
    doc.getPeople().add(TestFixture.INSTANCE.andy);
    doc.getPeople().add(TestFixture.INSTANCE.jamie);
    doc.getPeople().add(TestFixture.INSTANCE.bob);
    doc.getPeople().add(TestFixture.INSTANCE.eoin);
    doc.getJudges().add(TestFixture.INSTANCE.judgeAndy);
    doc.getJudges().add(TestFixture.INSTANCE.judgeJamie);
    doc.getJudges().add(TestFixture.INSTANCE.judgeBob);
    doc.getJudges().add(TestFixture.INSTANCE.judgeEoin);
    doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeAndy);
    doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeJamie);
    doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeBob);
    doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeEoin);

    String xml = XMLUtils.marshal(doc);

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpPost httpPost = new HttpPost(uri);

    StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    CloseableHttpResponse response = null;

    try {
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        doc = IntegrationTestUtils.convertEntity(responseEntity);

        for (HiredJudge j : doc.getHiredJudges()) {
            if (j.getJudge().getId().equals(TestFixture.INSTANCE.judgeAndy.getId())) {
                TestFixture.INSTANCE.hiredJudgeAndy.setId(j.getId());
            } else if (j.getJudge().getId().equals(TestFixture.INSTANCE.judgeBob.getId())) {
                TestFixture.INSTANCE.hiredJudgeBob.setId(j.getId());
            } else if (j.getJudge().getId().equals(TestFixture.INSTANCE.judgeJamie.getId())) {
                TestFixture.INSTANCE.hiredJudgeJamie.setId(j.getId());
            } else if (j.getJudge().getId().equals(TestFixture.INSTANCE.judgeEoin.getId())) {
                TestFixture.INSTANCE.hiredJudgeEoin.setId(j.getId());
            }
        }

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }
}