Example usage for org.apache.http.util EntityUtils toString

List of usage examples for org.apache.http.util EntityUtils toString

Introduction

In this page you can find the example usage for org.apache.http.util EntityUtils toString.

Prototype

public static String toString(HttpEntity httpEntity, String str) throws IOException, ParseException 

Source Link

Usage

From source file:ee.ioc.phon.netspeechapi.Utils.java

/**
 * <p>Executes the given HTTP request using the given HTTP client,
 * and returns the received entity as string.
 * Returns <code>null</code> if the query was performed (i.e. the server
 * was reachable) but resulted in a failure,
 * e.g. 404 error.</p>/* www.  j a v  a 2 s  . c  o  m*/
 * 
 * @param client HTTP client
 * @param request HTTP request (e.g. GET or POST)
 * @return response as String
 * @throws IOException
 */
public static String getResponseEntityAsString(HttpClient client, HttpUriRequest request) throws IOException {
    try {
        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();

        if (entity == null) {
            return null;
        }
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            return null;
        }
        if (entity.getContentEncoding() == null) {
            return EntityUtils.toString(entity, HTTP.UTF_8);
        }
        return EntityUtils.toString(entity);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.cats.version.utils.Utils.java

public static String postMsgAndGet(String msg) {
    HttpPost request = new HttpPost(UserPreference.getInstance().getUrl());
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("msg", msg));

    try {//from  w  w  w. ja va  2 s. c o m
        UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(parameters, IVersionConstant.CHARSET_UTF8);
        request.setEntity(formEntiry);
        HttpResponse response = client.execute(request);
        if (response.getStatusLine().getStatusCode() == 200) {
            return EntityUtils.toString(response.getEntity(), IVersionConstant.CHARSET_UTF8);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:wuit.common.crawler.WebSit.Crawler.java

public static String doGetHttp(DSCrawlerUrl pageUrl) {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 12000);
    HttpConnectionParams.setSoTimeout(params, 9000);
    HttpClient httpclient = new DefaultHttpClient(params);
    String rs = "";
    try {//from   w w  w .  ja  v a2 s  . c om
        HttpGet httpget = new HttpGet(pageUrl.url);
        //            System.out.println("executing request " + pageUrl.url);
        HttpContext httpContext = new BasicHttpContext();
        //            httpget.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
        httpget.addHeader("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)");

        HttpResponse response = httpclient.execute(httpget, httpContext);
        HttpUriRequest realRequest = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
        HttpHost targetHost = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        pageUrl.url = targetHost.toString() + realRequest.getURI();
        int resStatu = response.getStatusLine().getStatusCode();//? 
        if (resStatu == 200) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                rs = EntityUtils.toString(entity, "iso-8859-1");
                String in_code = getEncoding(rs);
                String encode = getHtmlEncode(rs);
                if (encode.isEmpty()) {
                    httpclient.getConnectionManager().shutdown();
                    return "";
                } else {
                    if (!in_code.toLowerCase().equals("utf-8")
                            && !in_code.toLowerCase().equals(encode.toLowerCase())) {
                        if (!in_code.toLowerCase().equals("iso-8859-1"))
                            rs = new String(rs.getBytes("iso-8859-1"), in_code);
                        if (!encode.toLowerCase().equals(in_code.toLowerCase()))
                            rs = new String(rs.getBytes(in_code), encode);
                    }
                }
                try {
                } catch (RuntimeException ex) {
                    httpget.abort();
                    throw ex;
                } finally {
                    // Closing the input stream will trigger connection release
                    //                    try { instream.close(); } catch (Exception ignore) {}
                }
            }
        }
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
        return rs;
    }
}

From source file:com.zhch.example.commons.http.v4_5.ClientExecuteProxy.java

public static void proxyExample() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*w  w  w .j  av  a 2  s  . co m*/
        HttpHost proxy = new HttpHost("24.157.37.61", 8080, "http");

        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpGet request = new HttpGet("http://www.ip.cn");
        request.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1");

        request.setConfig(config);

        System.out.println(
                "Executing request " + request.getRequestLine() + " to " + request.getURI() + " via " + proxy);

        CloseableHttpResponse response = httpclient.execute(request);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity(), "utf8"));
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:hobbyshare.testclient.RestService_TestClient.java

public void test_Login() {
    HttpClient httpClient = HttpClientBuilder.create().build();

    JSONObject loginAttempt = new JSONObject();
    loginAttempt.put("password", "1234");
    loginAttempt.put("userName", "77_username");

    try {/*from   ww w .  j  a v  a2 s  .  co  m*/
        HttpPost request = new HttpPost("http://localhost:8095/login");
        StringEntity params = new StringEntity(loginAttempt.toString());
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);

        System.out.println("---Testing Login----");
        System.out.println(response.toString());
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity, "UTF-8");
        System.out.println(responseString);
        System.out.println("----End of login Test----");
    } catch (Exception ex) {
        // handle exception here
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.elasticsearch.upgrades.WatcherRestartIT.java

private void ensureWatcherStarted() throws Exception {
    assertBusy(() -> {// www. j a v a  2 s  .c o m
        Response response = client().performRequest(new Request("GET", "_xpack/watcher/stats"));
        String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        assertThat(responseBody, containsString("\"watcher_state\":\"started\""));
        assertThat(responseBody, not(containsString("\"watcher_state\":\"starting\"")));
        assertThat(responseBody, not(containsString("\"watcher_state\":\"stopping\"")));
        assertThat(responseBody, not(containsString("\"watcher_state\":\"stopped\"")));
    });
}

From source file:com.ibm.watson.app.common.util.rest.StringResponseHandler.java

@Override
protected String handleEntity(HttpEntity entity) throws IOException {
    return EntityUtils.toString(entity, charset);
}

From source file:com.wudaosoft.net.httpclient.JsonResponseHandler.java

@Override
public JSONObject handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
    int status = response.getStatusLine().getStatusCode();
    if (status >= 200 && status < 300) {
        HttpEntity entity = response.getEntity();
        Charset charset = ContentType.getOrDefault(entity).getCharset();
        if (charset == null) {
            charset = Consts.UTF_8;/*from  www  .  jav  a  2  s .  c  o  m*/
        }
        try {
            return entity != null ? JSON.parseObject(EntityUtils.toString(entity, charset)) : new JSONObject();
        } catch (JSONException e) {
            throw new ClientProtocolException("Json format error: " + e.getMessage());
        }
    } else {
        throw new ClientProtocolException("Unexpected response status: " + status);
    }
}

From source file:coolmapplugin.util.HTTPRequestUtil.java

public static String executeGet(String targetURL) {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {

        HttpGet request = new HttpGet(targetURL);

        HttpResponse result = httpClient.execute(request);

        // TODO if there exists any other 20*
        if (result.getStatusLine().getStatusCode() != 200) {
            return null;
        }/*  w  ww .  j  ava2  s.  c o m*/

        String jsonResult = EntityUtils.toString(result.getEntity(), "UTF-8");

        return jsonResult;

    } catch (IOException e) {
        return null;
    }
}

From source file:com.jubination.io.chatbot.backend.service.core.DashBotUpdater.java

public String sendAutomatedUpdate(DashBot dashbot, String type) {
    String responseText = "";
    try {//w  ww .  ja v a2  s .  c o m
        String url = "https://tracker.dashbot.io/track?platform=generic&v=0.8.2-rest&type=" + type
                + "&apiKey=bJt7U0oEG79HSUm4nJWUQTPm1nhjKu3gieZ83M0O";
        ObjectMapper mapper = new ObjectMapper();
        //Object to JSON in String
        String jsonString = mapper.writeValueAsString(dashbot);
        HttpClient httpClient = HttpClientBuilder.create().build();
        // System.out.println(jsonString+"STRING JSON TO DASH BOT");
        StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
        HttpPost postMethod = new HttpPost(url);
        postMethod.setEntity(requestEntity);
        HttpResponse response = httpClient.execute(postMethod);
        HttpEntity entity = response.getEntity();
        responseText = EntityUtils.toString(entity, "UTF-8");

    } catch (Exception ex) {
        Logger.getLogger(DashBotUpdater.class.getName()).log(Level.SEVERE, null, ex);
    }
    // System.out.println(responseText);
    return responseText;
}