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:org.eclipse.lyo.testsuite.server.trsutils.HttpErrorHandler.java

/**
 * Handle a possible HTTP error response.
 * //  ww  w .  j  a va 2s  .c  o m
 * @param response
 *            The HTTP response to handle; must not be <code>null</code>
 * @throws HttpResponseException
 *             if the response status code maps to an exception class
 */
public static void responseToException(HttpResponse response) throws HttpResponseException {
    if (response == null)
        throw new IllegalArgumentException(Messages.getServerString("http.error.handler.null.argument")); //$NON-NLS-1$

    Integer status = Integer.valueOf(response.getStatusLine().getStatusCode());

    //Create detail message from response status line and body
    String reasonPhrase = response.getStatusLine().getReasonPhrase();

    StringBuilder message = new StringBuilder(reasonPhrase == null ? "" : reasonPhrase); //$NON-NLS-1$

    if (response.getEntity() != null) {
        try {
            String body = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
            if (body != null && body.length() != 0) {
                message.append('\n');
                message.append(body);
            }
        } catch (IOException e) {
        } // ignore, since the original error needs to be reported
    }

    throw new HttpResponseException(status, message.toString());
}

From source file:com.oneapm.base.tools.UrlPostMethod.java

public static String urlGetMethod(String url) {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpGet get = new HttpGet(url);
    HttpEntity entity = null;//from  w ww . j ava 2s.com
    String json = null;
    try {
        CloseableHttpResponse response = httpClient.execute(get);
        json = EntityUtils.toString(response.getEntity(), "UTF-8");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return json.toString();

}

From source file:org.plos.crepo.util.HttpResponseUtil.java

public static String getErrorMessage(HttpResponse response) {
    HttpEntity entity = response.getEntity();
    String responseMessage;/*from w w  w.  java2 s .c om*/
    String errorMessage;
    try {
        responseMessage = EntityUtils.toString(entity, CharEncoding.UTF_8);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    try {
        Gson gson = new Gson();
        JsonElement responseElement = gson.fromJson(responseMessage, JsonElement.class);
        JsonElement message = responseElement.getAsJsonObject().get("message");
        errorMessage = (message == null) ? "No error message" : message.getAsString();
    } catch (JsonSyntaxException e) { // Catch the possibles NOT JSON responses.
        errorMessage = "There was an error trying to obtain the JSON response error: "
                + response.getStatusLine();
    }
    return errorMessage;
}

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

private void ensureWatcherStopped() throws Exception {
    assertBusy(() -> {/*from   ww  w.  j av  a 2  s.  c om*/
        Response stats = client().performRequest(new Request("GET", "_xpack/watcher/stats"));
        String responseBody = EntityUtils.toString(stats.getEntity(), StandardCharsets.UTF_8);
        assertThat(responseBody, containsString("\"watcher_state\":\"stopped\""));
        assertThat(responseBody, not(containsString("\"watcher_state\":\"starting\"")));
        assertThat(responseBody, not(containsString("\"watcher_state\":\"started\"")));
        assertThat(responseBody, not(containsString("\"watcher_state\":\"stopping\"")));
    });
}

From source file:com.football.site.getdata.ScoreWebService.java

private static String GetHttpClientResponse(String url) {
    String responseText = "";
    try {//www  .  j a v  a2  s . com
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            httpGet.addHeader("X-Auth-Token", Constants.XAuthToken);
            httpGet.addHeader("Content-type", "application/json");
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            responseText = EntityUtils.toString(httpResponse.getEntity(), "ISO-8859-1");
            //logger.info(String.format("%s - %s", url, responseText));
        }
    } catch (IOException | ParseException e) {
        HelperUtil.AddErrorLog(logger, e);
        HelperUtil.AddErrorLogWithString(logger, url);
    }
    return responseText;
}

From source file:com.fengduo.bee.commons.util.HttpClientUtils.java

public static String postRequest(String url, List<NameValuePair> postParams) throws Exception {
    HttpPost post = new HttpPost(url);
    UrlEncodedFormEntity uefEntity;/*from   ww  w.  j a  va  2s  .  c o  m*/
    String result = null;
    try {
        uefEntity = new UrlEncodedFormEntity(postParams, CHARSET);
        post.setEntity(uefEntity);
        HttpResponse rep = client.execute(post);
        if (rep.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity httpEntity = rep.getEntity();
            if (httpEntity != null) {
                result = EntityUtils.toString(httpEntity, "UTF-8");
            }
        }

    } catch (Exception e) {
        throw e;
    } finally {
        post.abort();
    }
    return result;
}

From source file:Main.java

/**
 * Op Http post request , "404error" response if failed
 * //from w ww .j a  v a2  s. c  o  m
 * @param url
 * @param map
 *            Values to request
 * @return
 */

static public String doHttpPost(String url, HashMap<String, String> map) {

    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), TIMEOUT);
    HttpConnectionParams.setSoTimeout(client.getParams(), TIMEOUT);
    ConnManagerParams.setTimeout(client.getParams(), TIMEOUT);
    HttpPost post = new HttpPost(url);
    post.setHeaders(headers);
    String result = "ERROR";
    ArrayList<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
    if (map != null) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            BasicNameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
            pairList.add(pair);
        }

    }
    try {
        HttpEntity entity = new UrlEncodedFormEntity(pairList, "UTF-8");
        post.setEntity(entity);
        HttpResponse response = client.execute(post);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

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

        } else {
            result = EntityUtils.toString(response.getEntity(), "UTF-8")
                    + response.getStatusLine().getStatusCode() + "ERROR";
        }

    } catch (ConnectTimeoutException e) {
        result = "TIMEOUTERROR";
    }

    catch (Exception e) {
        result = "OTHERERROR";
        e.printStackTrace();

    }
    return result;
}

From source file:org.mobicents.servlet.restcomm.util.HttpUtils.java

public static Map<String, String> toMap(final HttpEntity entity) throws IllegalStateException, IOException {

    String contentType = null;//from  w  ww .  ja  v a  2s. com
    String charset = null;

    contentType = EntityUtils.getContentMimeType(entity);
    charset = EntityUtils.getContentCharSet(entity);

    List<NameValuePair> parameters = null;
    if (contentType != null && contentType.equalsIgnoreCase(CONTENT_TYPE)) {
        parameters = URLEncodedUtils.parse(entity);
    } else {
        final String content = EntityUtils.toString(entity, HTTP.ASCII);
        if (content != null && content.length() > 0) {
            parameters = new ArrayList<NameValuePair>();
            URLEncodedUtils.parse(parameters, new Scanner(content), charset);
        }
    }

    final Map<String, String> map = new HashMap<String, String>();
    for (final NameValuePair parameter : parameters) {
        map.put(parameter.getName(), parameter.getValue());
    }
    return map;
}

From source file:com.qwazr.utils.http.StringHttpResponseHandler.java

public String handleResponse(HttpResponse response) throws IOException {
    super.handleResponse(response);
    return EntityUtils.toString(httpEntity, CharsetUtils.CharsetUTF8);
}

From source file:org.openo.nfvo.emsdriver.northbound.client.HttpClientUtil.java

public static String doPost(String url, String json, String charset) {
    CloseableHttpClient httpClient = null;
    HttpPost httpPost = null;//from  w  ww .j a  va 2 s. c o m
    String result = null;
    try {
        httpClient = HttpClientFactory.getSSLClientFactory();
        httpPost = new HttpPost(url);
        if (null != json) {
            StringEntity s = new StringEntity(json);
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json"); // set contentType
            httpPost.setEntity(s);
        }
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception e) {
            log.error("httpClient.execute(httpPost) is fail", e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
    } catch (Exception e) {
        log.error("doPost is fail ", e);
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
            }
        }

    }
    return result;
}