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) throws IOException, ParseException 

Source Link

Usage

From source file:org.fcrepo.auth.oauth.integration.api.TokenEndpointIT.java

@Test
public void testGetToken() throws Exception {
    logger.trace("Entering testGetToken()...");
    final HttpPost post = new HttpPost(
            tokenEndpoint + "?grant_type=password&username=foo&password=bar&client_secret=foo&client_id=bar");
    post.addHeader("Accept", APPLICATION_JSON);
    post.addHeader("Content-type", APPLICATION_FORM_URLENCODED);
    final HttpResponse tokenResponse = client.execute(post);
    logger.debug("Got a token response: \n{}", EntityUtils.toString(tokenResponse.getEntity()));
    assertEquals("Couldn't retrieve a token from token endpoint!", 200,
            tokenResponse.getStatusLine().getStatusCode());

}

From source file:com.google.developers.gdgfirenze.mockep.AndroidSimulator.java

private static void postData(String url, JSONObject jsonSamplePacket)
        throws ClientProtocolException, IOException {

    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, 10000);
    HttpConnectionParams.setSoTimeout(myParams, 10000);
    HttpClient httpclient = new DefaultHttpClient(myParams);

    HttpPost httppost = new HttpPost(url.toString());
    httppost.setHeader("Content-type", "application/json");

    StringEntity se = new StringEntity(jsonSamplePacket.toString());
    se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    httppost.setEntity(se);/*www . java 2  s.c o  m*/

    HttpResponse response = httpclient.execute(httppost);

    String temp = EntityUtils.toString(response.getEntity());
    System.out.println("JSON post response: " + temp);
}

From source file:gobblin.http.ApacheHttpRequest.java

@Override
public String toString() {
    HttpUriRequest request = getRawRequest();
    StringBuilder outBuffer = new StringBuilder();
    String endl = "\n";
    outBuffer.append("ApacheHttpRequest Info").append(endl);
    outBuffer.append("type: HttpUriRequest").append(endl);
    outBuffer.append("uri: ").append(request.getURI().toString()).append(endl);
    outBuffer.append("headers: ");
    Arrays.stream(request.getAllHeaders()).forEach(header -> outBuffer.append("[").append(header.getName())
            .append(":").append(header.getValue()).append("] "));
    outBuffer.append(endl);/*www  . j  a  va 2s.  c o  m*/

    if (request instanceof HttpEntityEnclosingRequest) {
        try {
            String body = EntityUtils.toString(((HttpEntityEnclosingRequest) request).getEntity());
            outBuffer.append("body: ").append(body).append(endl);
        } catch (IOException e) {
            outBuffer.append("body: ").append(e.getMessage()).append(endl);
        }
    }
    return outBuffer.toString();
}

From source file:org.fcrepo.indexer.integration.webapp.FedoraIndexerIT.java

@Test
public void testReindex() throws IOException {
    HttpPost reindex = new HttpPost(serverAddress + "/reindex/");
    HttpResponse response = client.execute(reindex);
    assertEquals(200, response.getStatusLine().getStatusCode());
    assertEquals("Reindexing started\n", EntityUtils.toString(response.getEntity()));
}

From source file:com.example.fangyichen.demomaps.IpInfoDbClient.java

public static void getGeoAddressFromIP(String ipAddress) throws IOException {
    String url = "http://api.ipinfodb.com/v3/" + MODE + "/?format=json&key=" + APIKEY + "&ip=" + ipAddress;
    try {//from w ww.ja  v  a2  s .c  o  m
        HttpGet request = new HttpGet(url);
        HttpResponse response = HTTP_CLIENT.execute(request, new BasicHttpContext());
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new RuntimeException("IpInfoDb response is " + response.getStatusLine());
        }

        String responseBody = EntityUtils.toString(response.getEntity());
        IpCityResponse ipCityResponse = MAPPER.readValue(responseBody, IpCityResponse.class);
        if ("OK".equals(ipCityResponse.getStatusCode())) {
            System.out.println(ipCityResponse.getCountryCode() + ", " + ipCityResponse.getRegionName() + ", "
                    + ipCityResponse.getCityName());

        } else {
            System.out.println("API status message is '" + ipCityResponse.getStatusMessage() + "'");
        }
    } finally {
        HTTP_CLIENT.getConnectionManager().shutdown();
    }
}

From source file:com.rackspacecloud.client.service_registry.ClientResponse.java

private Object processResponse() throws IOException, ValidationException {
    Object data = null;//from w  ww  .j a  va2  s  .  co  m
    HttpEntity entity = this.response.getEntity();
    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode == 400) {
        data = EntityUtils.toString(entity);

        ValidationException ex = new Gson().fromJson(data.toString(), ValidationException.class);
        throw ex;
    }

    if (entity != null) {
        data = EntityUtils.toString(entity);

        if (this.parseAsJson && this.responseType != null) {
            GsonBuilder builder = new GsonBuilder();
            Gson gson = builder.registerTypeAdapter(Event.class, new Event()).create();
            data = gson.fromJson(data.toString(), this.responseType);
        }
    }

    return data;
}

From source file:org.kitodo.data.index.elasticsearch.type.BatchTypeTest.java

@Test
public void shouldCreateDocument() throws Exception {
    BatchType batchType = new BatchType();

    Batch batch = prepareData().get(0);/*from www  .ja  v a  2  s . co m*/
    HttpEntity document = batchType.createDocument(batch);
    String actual = EntityUtils.toString(document);
    String excepted = "{\"title\":\"Batch1\",\"type\":\"LOGISTIC\",\"processes\":[{\"id\":\"1\"},{\"id\":\"2\"}]}";
    assertEquals("Batch JSON string doesn't match to given plain text!", excepted, actual);

    batch = prepareData().get(1);
    document = batchType.createDocument(batch);
    actual = EntityUtils.toString(document);
    excepted = "{\"title\":\"Batch2\",\"type\":\"null\",\"processes\":[]}";
    assertEquals("Batch JSON string doesn't match to given plain text!", excepted, actual);
}

From source file:br.ufg.inf.horus.implementation.service.HttpRequest.java

/**
 * Mtodo que executa o POST./*  w w w .  j av a2s  . c om*/
 *
 * @see HttpInterface
 * @param url Url para a requisio.
 * @param body Mensagem da requisio.
 * @param log Objeto para exibio de mensagens Log (opcional).
 * @return Resposta da requisio.
 */
@Override
public String request(String url, String body, Log log) throws BsusException {

    BsusValidator.verifyNull(body, " body", log);
    BsusValidator.verifyNull(url, " url", log);

    String resposta = "";

    try {
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        StringEntity strEntity = new StringEntity(body, "UTF-8");
        strEntity.setContentType("text/xml");
        HttpPost post = new HttpPost(url);
        post.setEntity(strEntity);

        HttpResponse response = httpclient.execute(post);
        HttpEntity respEntity = response.getEntity();
        resposta = EntityUtils.toString(respEntity);

    } catch (IOException e) {
        String message = "Houve um erro ao abrir o documento .xml";
        BsusValidator.catchException(e, message, log);
    } catch (UnsupportedCharsetException e) {
        String message = "O charset 'UTF-8' da mensagem no esta sendo suportado.";
        BsusValidator.catchException(e, message, log);
    } catch (ParseException e) {
        String message = "Houve um erro ao buscar as informaes.";
        BsusValidator.catchException(e, message, log);
    }

    return resposta;
}

From source file:com.mashape.galileo.agent.network.AnalyticsResponseHandler.java

@Override
public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
    HttpEntity entity = response.getEntity();
    if (entity == null) {
        throw new ClientProtocolException("failed to save the batch");
    }//from ww  w .  ja v  a  2  s.  co  m

    StatusLine statusLine = response.getStatusLine();
    String responseBody = EntityUtils.toString(entity);
    if (statusLine.getStatusCode() == 200) {
        LOGGER.debug(String.format("successfully saved the batch. (%s)", responseBody));
        return true;
    }
    if (statusLine.getStatusCode() == 207) {
        LOGGER.warn(String.format("collector could not save all ALFs from the batch. (%s)", responseBody));
        return true;
    }
    if (statusLine.getStatusCode() == 400) {
        LOGGER.error(String.format(
                "collector refused to save the batch, dropping batch. Status: (%d) Reason: (%s) Error: (%s)",
                statusLine.getStatusCode(), statusLine.getReasonPhrase(), responseBody));
        return true;
    }
    if (statusLine.getStatusCode() == 413) {
        LOGGER.error(
                String.format("collector refused to save the batch, dropping batch. Status: (%d)  Error: (%s)",
                        statusLine.getStatusCode(), responseBody));
        return true;
    }
    LOGGER.error(String.format("failed to save the batch. Status: (%d)  Error: (%s)",
            statusLine.getStatusCode(), responseBody));
    return false;
}

From source file:windsekirun.qrreader.util.JsonReceiver.java

public String makeJsonCall(String url, int method, List<NameValuePair> params) {
    try {/*from  w  w w .  j a  v a 2s  .  c o  m*/
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity;
        HttpResponse httpResponse = null;

        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            if (params != null)
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            httpResponse = httpClient.execute(httpPost);
        } else if (method == GET) {
            if (params != null) {
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);
            httpResponse = httpClient.execute(httpGet);
        }
        assert httpResponse != null;
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;

}