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.rtl.http.Upload.java

private static String send(String message, InputStream fileIn, String url) throws Exception {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000)
            .build();// 
    post.setConfig(requestConfig);/*from  w w  w  .  j  a v  a2s .  c o  m*/
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setCharset(Charset.forName("UTF-8"));// ?
    ContentType contentType = ContentType.create("text/html", "UTF-8");
    builder.addPart("reqParam", new StringBody(message, contentType));
    builder.addPart("version", new StringBody("1.0", contentType));
    builder.addPart("dataFile", new InputStreamBody(fileIn, "file"));
    post.setEntity(builder.build());
    CloseableHttpResponse response = client.execute(post);
    InputStream inputStream = null;
    String responseStr = "", sCurrentLine = "";
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        inputStream = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((sCurrentLine = reader.readLine()) != null) {
            responseStr = responseStr + sCurrentLine;
        }
        return responseStr;
    }
    return null;
}

From source file:com.cht.imserver.push.TLPushNotification.java

public static PNResult pushMessage_Android(String token, String message, String sender, String licenseKey,
        PNServerType type, String proxy, int port)
        throws IOException, UnsupportedEncodingException, ClientProtocolException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpHost httpproxy = null;//from  ww w .j a  v a2s.c  o m
    String serverURL = null;
    PNResult result = null;
    if (type == PNServerType.android_dev) {
        serverURL = devAndroidHost;
    } else if (type == PNServerType.android_official) {
        serverURL = officialAndroidHost;
    }
    String jsontoken = "{\"androidTokens\":[{\"token\":\"" + token + "\"}]}";
    String jsonmessage = "{\"sender\":\"" + sender + "\",\"message\":\"" + message + "\"}";
    //System.out.println("androiddata=" + jsonmessage);
    //System.out.println("androidtoken=" + jsontoken);

    //logger.info("jsonmessage:" + jsonmessage + ", jsontoken:" + jsontoken + ", licenseKey:" + licenseKey );
    logger.info("jsonmessage:" + jsonmessage + ", licenseKey:" + licenseKey);

    try {
        HttpPost httpPost = new HttpPost(serverURL);
        if (proxy != null) {
            httpproxy = new HttpHost(proxy, port);
            RequestConfig config = RequestConfig.custom().setProxy(httpproxy).build();
            httpPost.setConfig(config);
        }
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("androiddata", jsonmessage));
        nvps.add(new BasicNameValuePair("androidtoken", jsontoken));
        nvps.add(new BasicNameValuePair("licensekey", licenseKey));
        nvps.add(new BasicNameValuePair("appname", appname));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        //System.out.println(EntityUtils.toString(httpPost.getEntity()) );

        CloseableHttpResponse response2 = httpclient.execute(httpPost);
        Gson mGson = new Gson();
        try {
            //System.out.println(response2.getStatusLine());
            HttpEntity entity2 = response2.getEntity();
            //System.out.println(EntityUtils.toString(entity2));
            result = mGson.fromJson(EntityUtils.toString(entity2), PNResult.class);

            EntityUtils.consume(entity2);

        } finally {
            response2.close();
        }
    } finally {
        httpclient.close();
    }
    return result;
}

From source file:com.helger.pd.client.jdk6.PDClient.java

@Nullable
private static String _getResponseString(@Nonnull final CloseableHttpResponse aResponse) throws IOException {
    final HttpEntity aResponseEntity = aResponse.getEntity();
    final String sResponse = aResponseEntity == null ? null
            : StreamHelper.getAllBytesAsString(aResponseEntity.getContent(), CCharset.CHARSET_UTF_8_OBJ);
    EntityUtils.consume(aResponseEntity);
    return sResponse;
}

From source file:com.cht.imserver.push.TLPushNotification.java

public static PNResult pushMessage_iOS(String token, String message, String lockey, String locargs,
        String sound, int badge, String licenseKey, PNServerType type, String proxy, int port)
        throws IOException, UnsupportedEncodingException, ClientProtocolException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpHost httpproxy = null;//from  w w  w .j a v a 2s  . c om
    String serverURL = null;
    PNResult result = null;
    if (type == PNServerType.ios_dev) {
        serverURL = deviOSHost;
    } else if (type == PNServerType.ios_official) {
        serverURL = officeialiOSHost;
    }
    String jsontoken = "{\"iosTokens\":[{\"token\":\"" + token + "\",\"badge\" : " + String.valueOf(badge)
            + "}]}";
    String jsonmessage = null;
    if (lockey == null || "".equals(lockey)) {
        jsonmessage = "{\"message\":\"" + message + "\",\"sound\":\"" + sound + "\"}";
    } else {
        jsonmessage = "{\"message\":\"" + message + "\",\"sound\":\"" + sound + "\",\"loc-key\":\"" + lockey
                + "\",\"loc-args\":" + locargs + "}";
    }
    //System.out.println("iosdata=" + jsonmessage);
    //System.out.println("iostoken=" + jsontoken);

    //logger.info("jsonmessage:" + jsonmessage + ", jsontoken:" + jsontoken + ", licenseKey:" + licenseKey );
    logger.info("jsonmessage:" + jsonmessage + ", licenseKey:" + licenseKey);

    try {
        HttpPost httpPost = new HttpPost(serverURL);
        if (proxy != null) {
            httpproxy = new HttpHost(proxy, port);
            RequestConfig config = RequestConfig.custom().setProxy(httpproxy).build();
            httpPost.setConfig(config);
        }
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("iosdata", jsonmessage));
        nvps.add(new BasicNameValuePair("iostoken", jsontoken));
        nvps.add(new BasicNameValuePair("licensekey", licenseKey));
        nvps.add(new BasicNameValuePair("appname", appname));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        //System.out.println(EntityUtils.toString(httpPost.getEntity()) );
        CloseableHttpResponse response2 = httpclient.execute(httpPost);
        Gson mGson = new Gson();
        try {
            //System.out.println(response2.getStatusLine());
            HttpEntity entity2 = response2.getEntity();
            //System.out.println(EntityUtils.toString(entity2));
            result = mGson.fromJson(EntityUtils.toString(entity2), PNResult.class);

            EntityUtils.consume(entity2);

        } finally {
            response2.close();
        }
    } finally {
        httpclient.close();
    }
    return result;

}

From source file:com.aws.image.test.TestFlickrAPI.java

public static String callFlickrAPIForEachKeyword(String query, String synsetCode, String safeSearch,
        int urlsPerKeyword) throws IOException, JSONException {
    String apiKey = "ad4f88ecfd53b17f93178e19703fe00d";
    String apiSecret = "96cab0e9f89468d6";

    int total = 500;
    int perPage = 500;

    System.out.println("\n\t\t KEYWORD::" + query);
    System.out.println("\t No. of urls required::" + urlsPerKeyword);
    int totalPages;
    if (urlsPerKeyword % perPage != 0)
        totalPages = (urlsPerKeyword / perPage) + 1;
    else// ww w .  j  ava  2 s.  co  m
        totalPages = urlsPerKeyword / perPage;

    System.out.println("\n\n\t total pages ::" + totalPages);

    int currentCount = 0;

    int eachPage;
    List<Document> documentsInBatch = new ArrayList<>();

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

        eachPage = urlsPerKeyword < perPage ? urlsPerKeyword : perPage;

        StringBuffer sb = new StringBuffer(512);
        sb.append("https://api.flickr.com/services/rest/?method=flickr.photos.search&text=")
                .append(URLEncoder.encode(query, "UTF-8")).append("&safe_search=").append(safeSearch)
                .append("&extras=url_c,url_m,url_n,license,owner_name&per_page=").append(eachPage)
                .append("&page=").append(i).append("&format=json&api_key=").append(apiKey)
                .append("&api_secret=").append(apiSecret).append("&license=4,5,6,7,8");

        String url = sb.toString();

        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());

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

        String inputLine;
        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
        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") : null;

            if (scrapedImageURL == null) {
                continue;
            }
            String contributor = tempObject.getString("ownername");
            String license = tempObject.getString("license");

            //System.out.println("Scraped Image URL, need to insert this to Mongo DB --> " + scrapedImageURL);

            //documentsInBatch.add(getDocumentPerCall(scrapedImageURL, contributor, license, safeSearch));

            counter++;

        }

        //insertData(documentsInBatch);
    }

    System.out.println("F L I C K R      C O U N T E R -> " + counter);
    //insertData(documentsInBatch);

    //countDownLatchForImageURLs.countDown();
    return null;
}

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

/**
 * ??// www.  j ava2s  . c om
 *
 * @param uri
 * @param params
 * @return
 */
public static String post(String uri, String params) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(uri);
    StringEntity stringEntity = new StringEntity(params, CHARSET.toString());
    httpPost.setEntity(stringEntity);
    try {
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            httpResponse.close();
            return EntityUtils.toString(httpResponse.getEntity(), CHARSET);
        }
    } catch (IOException e) {
        logger.error(":{}", e.getMessage());
    }
    return "";
}

From source file:com.mywork.framework.util.RemoteHttpUtil.java

/**
 * ?MultipartHttp??????ContentBody map/*www  . j ava  2 s  .c o  m*/
 */
public static String fetchMultipartHttpResponse(String contentUrl, Map<String, String> headerMap,
        Map<String, ContentBody> bodyMap) throws IOException {
    try {
        HttpPost httpPost = new HttpPost(contentUrl);
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        if (headerMap != null && !headerMap.isEmpty()) {
            for (Map.Entry<String, String> m : headerMap.entrySet()) {
                httpPost.addHeader(m.getKey(), m.getValue());
            }
        }
        if (bodyMap != null && !bodyMap.isEmpty()) {
            for (Map.Entry<String, ContentBody> m : bodyMap.entrySet()) {
                multipartEntityBuilder.addPart(m.getKey(), m.getValue());
            }
        }
        HttpEntity reqEntity = multipartEntityBuilder.build();
        httpPost.setEntity(reqEntity);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity resEntity = response.getEntity();
            String resStr = IOUtils.toString(resEntity.getContent());
            return resStr;
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            response.close();
        }

    } finally {
        httpClient.close();
    }
    return null;

}

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

private static void loadFormFile(String host, File file) {
    Scanner scan = null;/*w w w  .  ja v  a 2 s .co m*/
    try {
        scan = new Scanner(file, Loader.encoding);
        // the content is only the data portion.
        String content = scan.useDelimiter("\\Z").next();
        // convert to map
        Map<String, Object> newMap = ServiceLocator.getInstance().getMapper().readValue(content,
                new TypeReference<HashMap<String, Object>>() {
                });
        String formId = (String) newMap.get("formId");
        Map<String, Object> oldMap = (Map<String, Object>) formMap.get(formId);
        boolean changed = false;
        if (oldMap == null) {
            // never loaded before.
            changed = true;
        } else {
            if (newMap.get("action") != null && !newMap.get("action").equals(oldMap.get("action"))) {
                changed = true;
            }
            if (!changed && newMap.get("schema") != null
                    && !newMap.get("schema").equals(oldMap.get("schema"))) {
                changed = true;
            }
            if (!changed && newMap.get("form") != null && !newMap.get("form").equals(oldMap.get("form"))) {
                changed = true;
            }
            if (!changed && newMap.get("modelData") != null
                    && !newMap.get("modelData").equals(oldMap.get("modelData"))) {
                changed = true;
            }
        }
        if (changed) {
            Map<String, Object> inputMap = new HashMap<String, Object>();
            inputMap.put("category", "form");
            inputMap.put("name", "impForm");
            inputMap.put("readOnly", false);

            Map<String, Object> data = new HashMap<String, Object>();
            data.put("content", content);
            inputMap.put("data", data);
            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);
            CloseableHttpResponse response = httpclient.execute(httpPost);

            try {
                System.out.println("Form: " + file.getAbsolutePath() + " is loaded with status "
                        + response.getStatusLine());
                HttpEntity entity = response.getEntity();
                BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
                String json = "";
                String line = "";
                while ((line = rd.readLine()) != null) {
                    json = json + line;
                }
                //System.out.println("json = " + json);
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        if (scan != null)
            scan.close();
    }
}

From source file:org.keycloak.testsuite.saml.ConcurrentAuthnRequestTest.java

public static void performLogin(HttpUriRequest post, URI samlEndpoint, String relayState, Document samlRequest,
        CloseableHttpResponse response, final CloseableHttpClient client, UserRepresentation user,
        RedirectStrategyWithSwitchableFollowRedirect strategy) {
    try {/*w ww .j ava2s.  co  m*/
        HttpClientContext context = HttpClientContext.create();
        response = client.execute(post, context);

        String loginPageText = EntityUtils.toString(response.getEntity(), "UTF-8");
        response.close();

        HttpUriRequest loginRequest = LoginBuilder.handleLoginPage(user, loginPageText);

        strategy.setRedirectable(false);
        response = client.execute(loginRequest, context);
        response.close();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        if (response != null) {
            EntityUtils.consumeQuietly(response.getEntity());
            try {
                response.close();
            } catch (IOException ex) {
            }
        }
    }
}

From source file:edu.mit.scratch.Scratch.java

protected static String consume(final CloseableHttpResponse r) throws IllegalStateException, IOException {
    final InputStream in = r.getEntity().getContent();
    final StringBuffer str = new StringBuffer();
    final byte[] b = new byte[64];
    int len;/*from w w w.  j a  v a  2 s.c o m*/
    while ((len = in.read(b)) != -1)
        str.append(new String(b, 0, len));
    in.close();
    return str.toString();
}