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:com.lurencun.cfuture09.androidkit.http.async.EntityHttpResponseHandler.java

void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    String responseBody = null;/*from w  w w  . j  ava  2s. co  m*/
    try {
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
            responseBody = EntityUtils.toString(entity, "UTF-8");
        }
    } catch (IOException e) {
        sendFailureMessage(e, (String) null);
    }

    if (status.getStatusCode() >= 300) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                responseBody);
    } else {
        sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), response.getEntity());
    }
}

From source file:de.escidoc.core.test.sm.PreprocessingTestBase.java

/**
 * Test preprocessing raw statistic data.
 *
 * @param dataXml                 The preprocessing-information xml.
 * @param aggregationDefinitionId The id of the aggregationDefinition to preprocess.
 * @return The created item.//from   ww  w  .  j  ava  2  s . com
 * @throws Exception If anything fails.
 */
public String preprocess(final String aggregationDefinitionId, final String dataXml) throws Exception {

    Object result = getPreprocessingClient().preprocess(aggregationDefinitionId, dataXml);
    String xmlResult = null;
    if (result instanceof HttpResponse) {
        HttpResponse httpRes = (HttpResponse) result;
        xmlResult = EntityUtils.toString(httpRes.getEntity(), HTTP.UTF_8);

        assertHttpStatusOfMethod("", httpRes);

    } else if (result instanceof String) {
        xmlResult = (String) result;
    }
    return xmlResult;
}

From source file:de.escidoc.core.test.sm.AggregationDefinitionTestBase.java

/**
 * Test creating aggregationDefinition.// w ww .ja  v a 2 s .co  m
 *
 * @param dataXml The xml representation of the aggregationDefinition.
 * @return The created aggregationDefinition.
 * @throws Exception If anything fails.
 */
@Override
public String create(final String dataXml) throws Exception {

    Object result = getAggregationDefinitionClient().create(dataXml);
    String xmlResult = null;
    if (result instanceof HttpResponse) {
        HttpResponse httpRes = (HttpResponse) result;
        xmlResult = EntityUtils.toString(httpRes.getEntity(), HTTP.UTF_8);
        assertHttpStatusOfMethod("", httpRes);
    } else if (result instanceof String) {
        xmlResult = (String) result;
    }
    return xmlResult;
}

From source file:org.bishoph.oxdemo.util.GetTaskList.java

@Override
protected JSONObject doInBackground(Object... params) {
    try {//w  ww . j a v a 2 s.  c o m
        String uri = (String) params[0];
        Log.v("OXDemo", "Attempting to get task list " + uri);
        HttpGet httpget = new HttpGet(uri);
        httpget.setHeader("Accept", "application/json, text/javascript");
        HttpResponse response = httpclient.execute(httpget, localcontext);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, HTTP.UTF_8);
        Log.d("OXDemo", "<<<<<<<\n" + result + "\n\n");
        JSONObject jsonObj = new JSONObject(result);
        return jsonObj;
    } catch (JSONException e) {
        Log.e("OXDemo", e.getMessage());
    } catch (ClientProtocolException e) {
        Log.e("OXDemo", e.getMessage());
    } catch (IOException e) {
        Log.e("OXDemo", e.getMessage());
    }
    return null;
}

From source file:com.ibm.watson.developer_cloud.util.ResponseUtil.java

/**
 * Returns a String representation of the response.
 * //from  ww  w  .j a va 2  s  . com
 * @param response
 *            an HTTP response
 * @return the content body as String
 * @throws IOException
 *             network error
 * */
public static String getString(HttpResponse response) throws IOException {
    HttpEntity entity;
    try {
        entity = response.getEntity();
        if (entity == null)
            return null;
        else
            return EntityUtils.toString(entity, "UTF-8");
    } catch (ParseException e) {
        log.log(Level.SEVERE, "Could not parse service response", e);
        throw new IOException("Could not parse service response:" + e.getMessage());
    } catch (IOException e) {
        log.log(Level.SEVERE, "Could not read service response", e);
        throw new IOException("Could not read service response:" + e.getMessage());
    }
}

From source file:com.kkurahar.locationmap.HttpConnection.java

public String doGet(String url) {

    HttpGet method = new HttpGet(url);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    method.setHeader("Connection", "Keep-Alive");
    try {//from   w w  w . j a  va2  s  . c o  m

        String resultRes = httpClient.execute(method, new ResponseHandler<String>() {

            @Override
            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                // Xe?[^XR?[h
                int status = response.getStatusLine().getStatusCode();
                if (HttpStatus.SC_OK == status) {
                    Header[] headers = response.getAllHeaders();
                    for (Header h : headers) {
                        System.out.println(h.getName() + ":" + h.getValue());
                    }
                } else {
                    throw new RuntimeException("?MG?[?");
                }
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        });
        return resultRes;
    } catch (ClientProtocolException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}

From source file:com.ibm.ra.remy.web.utils.BusinessRulesUtils.java

/**
 * Invoke Business Rules with JSON content
 *
 * @param content The payload of itineraries to send to Business Rules.
 * @return A JSON string representing the output of Business Rules.
 *//*  ww w.j  a  va 2 s  .  c o  m*/
public static String invokeRulesService(String json) throws Exception {
    PropertiesReader constants = PropertiesReader.getInstance();
    String username = constants.getStringProperty(USERNAME_KEY);
    String password = constants.getStringProperty(PASSWORD_KEY);
    String endpoint = constants.getStringProperty(EXECUTION_REST_URL_KEY)
            + constants.getStringProperty(RULE_APP_PATH_KEY);

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(credentialsProvider).build();

    String responseString = "";

    try {
        HttpPost httpPost = new HttpPost(endpoint);
        httpPost.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
        StringEntity jsonEntity = new StringEntity(json, MessageUtils.ENCODING);
        httpPost.setEntity(jsonEntity);
        CloseableHttpResponse response = httpClient.execute(httpPost);

        try {
            HttpEntity entity = response.getEntity();
            responseString = EntityUtils.toString(entity, MessageUtils.ENCODING);
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpClient.close();
    }
    return responseString;
}

From source file:de.utkast.encoding.EncodingTestClient.java

@Test
public void testEncoding() throws Exception {

    String input = "?? ?";
    String url = "http://localhost:8080/restful-encoding/enc";

    EncodingDTO dto = new EncodingDTO(input);

    JAXBContext ctx = JAXBContext.newInstance(EncodingDTO.class);
    StringWriter writer = new StringWriter();
    ctx.createMarshaller().marshal(dto, writer);

    System.out.println(String.format("Will send: %s", writer.toString()));

    HttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(url);
    HttpEntity entity = new ByteArrayEntity(writer.toString().getBytes("UTF-8"));
    post.setEntity(entity);//from  w  w  w.  ja v  a2  s .co m
    post.setHeader("Content-Type", "application/xml;charset=UTF-8");
    post.setHeader("Accept", "application/xml;charset=UTF-8");

    HttpResponse response = client.execute(post);
    String output = EntityUtils.toString(response.getEntity(), "UTF-8");

    assertEquals(writer.toString(), output);
}

From source file:com.currencyfair.minfraud.MinFraudImpl.java

@Override
public RiskScoreResponse calculateRisk(RiskScoreRequest request) throws IOException {
    HttpPost req = methodFactory.createPost(endpoint.get());
    List<NameValuePair> params = createParams(request);
    LOG.trace("Request parameters: {}", params);
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, Consts.UTF_8);
    req.setEntity(entity);//from   www  .j  ava2  s . co  m
    HttpResponse resp = httpClient.execute(req);
    try (CloseableHttpResponseAdapter adapter = new CloseableHttpResponseAdapter(resp)) {
        int statusCode = resp.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            String responseValues = EntityUtils.toString(resp.getEntity(), Consts.ISO_8859_1);
            LOG.trace("minFraud response: {}", responseValues);
            RiskScoreResponse riskScore = RiskScoreResponse.extract(parseValueMap(responseValues));
            riskScore.setRawResponse(responseValues);
            return riskScore;
        } else {
            throw new IOException("Unexpected response code from remote: " + statusCode);
        }
    }
}

From source file:coyote.dx.web.worker.HtmlWorker.java

/**
 * @see coyote.dx.web.worker.AbstractWorker#marshalResponseBody(coyote.dx.web.Response, org.apache.http.HttpResponse, coyote.dx.web.Parameters)
 *//*from   w w  w .  ja v a2s. c  o m*/
@Override
public void marshalResponseBody(final Response workerResponse, final HttpResponse httpResponse,
        final Parameters params) {
    try {
        // Use Content-Encoding to properly parse the body
        final org.apache.http.entity.ContentType ctype = org.apache.http.entity.ContentType
                .getOrDefault(httpResponse.getEntity());
        final String body = EntityUtils.toString(httpResponse.getEntity(), ctype.getCharset());

        final Document document = Jsoup.parse(body);
        workerResponse.setDocument(document);
        return;
    } catch (final Exception e) {
        Log.error("Problems parsing HTML: " + e.getClass().getSimpleName() + " - " + e.getMessage());
    }
    super.marshalResponseBody(workerResponse, httpResponse, params);
}