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:Services.Leer.java

public JSONArray leer(String ruta) throws ClientProtocolException, IOException, JSONException {

    HttpClient client = new DefaultHttpClient();
    int id = 1;//from  ww w  .jav  a 2  s  . c  o m
    // HttpGet get = new HttpGet("http://ip.no-ip.org:8000/ruta");
    HttpGet get = new HttpGet(ruta);

    HttpResponse response = client.execute(get);
    HttpEntity entity = response.getEntity();
    String content = EntityUtils.toString(entity);
    System.out.println("ESTE ES EL JSON en LEER " + content);

    JSONArray json = new JSONArray(content);

    return json;
}

From source file:myexamples.MyExamples.java

public static void getExample() throws IOException {
    HttpGet httpGet = new HttpGet("http://localhost:9200/gb/tweet/9");
    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    // The underlying HTTP connection is still held by the response object
    // to allow the response content to be streamed directly from the network socket.
    // In order to ensure correct deallocation of system resources
    // the user MUST call CloseableHttpResponse#close() from a finally clause.
    // Please note that if response content is not fully consumed the underlying
    // connection cannot be safely re-used and will be shut down and discarded
    // by the connection manager.
    try {// w  w w. ja v  a 2 s.co  m
        System.out.println(response1.getStatusLine());
        HttpEntity entity1 = response1.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        if (entity1 != null) {
            long len = entity1.getContentLength();
            if (len != -1 && len < 2048) {
                System.out.println(EntityUtils.toString(entity1));
            } else {
                System.out.println("entity length=" + len);
            }
        }

        EntityUtils.consume(entity1);
    } finally {
        response1.close();
    }
}

From source file:br.pub.tradutor.TradutorController.java

/**
 * Mtodo utilizado para traduo utilizando o Google Translate
 *
 * @param text Texto a ser traduzido/*  www .  j  a va  2  s  . c  o  m*/
 * @param from Idioma de origem
 * @param to Idioma de destino
 * @return Texto traduzido (no idioma destino)
 * @throws IOException
 */
public static String translate(String text, String from, String to) throws IOException {
    //Faz encode de URL, para fazer escape dos valores que vo na URL
    String encodedText = URLEncoder.encode(text, "UTF-8");

    DefaultHttpClient httpclient = new DefaultHttpClient();

    //Mtodo GET a ser executado
    HttpGet httpget = new HttpGet(String.format(TRANSLATOR, encodedText, from, to));

    //Faz a execuo
    HttpResponse response = httpclient.execute(httpget);

    //Busca a resposta da requisio e armazena em String
    String returnContent = EntityUtils.toString(response.getEntity());

    //Desconsidera tudo depois do primeiro array
    returnContent = returnContent.split("\\],\\[")[0];

    //StringBuilder que sera carregado o retorno
    StringBuilder translatedText = new StringBuilder();

    //Verifica todas as tradues encontradas, e junta todos os trechos
    Matcher m = RESULTS_PATTERN.matcher(returnContent);
    while (m.find()) {
        translatedText.append(m.group(1).trim()).append(' ');
    }

    //Retorna
    return translatedText.toString().trim();

}

From source file:es.uvigo.esei.dai.hybridserver.utils.TestUtils.java

/**
 * Realiza una peticin por GET y devuelve el contenido de la respuesta.
 * // w ww  . jav a  2s.  co m
 * La peticin se hace en UTF-8 y solicitando el cierre de la conexin.
 * 
 * Este mtodo comprueba que el cdigo de respuesta HTTP sea 200 OK.
 * 
 * @param url URL de la pgina solicitada.
 * @return contenido de la respuesta HTTP.
 * @throws IOException en el caso de que se produzca un error de conexin.
 */
public static String getContent(String url) throws IOException {
    final HttpResponse response = Request.Get(url).addHeader("Connection", "close")
            .addHeader("Content-encoding", "UTF-8").execute().returnResponse();

    assertEquals(200, response.getStatusLine().getStatusCode());

    return EntityUtils.toString(response.getEntity());
}

From source file:org.andrico.andjax.http.HttpResponseRunnable.java

/**
 * Retrieve the string contents of the Entity attached to an http response.
 * //from   w  ww .j  a  v  a2  s.  c  o  m
 * @param response The response to pull the (String)entity from.
 * @return The contents of the entity from a string or null if there were
 *         any errors.
 */
public static String httpResponseToString(HttpResponse response) {
    String responseString = null;
    try {
        responseString = EntityUtils.toString(response.getEntity());
    } catch (ParseException e) {
        Log.d(TAG, "ParseException, its likely there was a network issue.");
    } catch (IOException e) {
        Log.d(TAG, "IOException, its likely there was a network issue.");
    } catch (NullPointerException e) {
        Log.d(TAG, "NullPointerException, its likely there was a network issue.");
    }

    if (responseString != null) {
        Log.d(TAG, responseString);
    }
    return responseString;
}

From source file:cn.hi321.browser.weave.client.WeaveResponse.java

public WeaveResponse(HttpResponse response) throws IOException {
    m_responseHeaders = new WeaveTransport.WeaveResponseHeaders(response);
    HttpEntity entity = response.getEntity();
    m_body = entity == null ? null : EntityUtils.toString(entity);
}

From source file:com.almende.arum.RESTEndpoint.java

/**
 * Gets the job.// w ww.j a  v a 2 s.  c o  m
 */
public void getJob() {

    String url = "http://95.211.177.143:8080/arum/fnsd/production/jobs/";
    HttpGet httpGet = new HttpGet(URI.create(url));
    try {
        httpGet.addHeader("Accept", "application/json");
        HttpResponse resp = client.execute(httpGet);
        String responseBody = EntityUtils.toString(resp.getEntity());
        ArrayNode tree = (ArrayNode) JOM.getInstance().readTree(responseBody);

        if (oldData != null) {

        }
        oldData = tree;

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (httpGet != null) {
            httpGet.reset();
        }
    }
}

From source file:org.apache.usergrid.apm.service.UsergridInternalRestServerConnector.java

public static boolean isCrashNotificationDisabled(String orgName, String appName) {
    String restServerUrl = DeploymentConfig.geDeploymentConfig().getUsergridRestUrl();
    //String restServerUrl = "http://instaops-apigee-mobile-app-prod.apigee.net/";
    restServerUrl += "/" + orgName + "/" + appName + "/apm/apigeeMobileConfig";
    log.info("Checking if crash notification is disabled for " + orgName + " app : " + appName);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet getMethod = new HttpGet(restServerUrl);
    HttpResponse response;/*from  w  w  w. j  a  v a  2s  .  c o m*/
    try {
        response = httpClient.execute(getMethod);

        HttpEntity entity = response.getEntity();
        String jsonObject = EntityUtils.toString(entity);
        ObjectMapper mapper = new ObjectMapper();
        App app = mapper.readValue(jsonObject, App.class);
        Set<AppConfigCustomParameter> parameters = app.getDefaultAppConfig().getCustomConfigParameters();
        for (AppConfigCustomParameter param : parameters) {
            if (param.getTag().equalsIgnoreCase("ALARM")
                    && param.getParamKey().equalsIgnoreCase("SUPPRESS_ALARMS")
                    && param.getParamValue().equalsIgnoreCase("TRUE"))
                ;
            {
                return true;
            }
        }

    } catch (ClientProtocolException e) {
        log.error("Problem connectiong to Usergrid internal REST server " + restServerUrl);
        e.printStackTrace();

    } catch (IOException e) {
        log.error("Problem connectiong to Usergrid internal REST server " + restServerUrl);
        e.printStackTrace();
    }
    httpClient = null;
    return false;
}

From source file:org.openmrs.contrib.discohub.HttpUtils.java

public static Map<String, Object> getData(String url, Header[] headers) throws IOException {
    final Map<String, Object> responseMap = new LinkedHashMap<>();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet(url);
    httpget.setHeaders(headers);/*  w w  w  . j a v a 2s  . com*/

    // Create a custom response handler
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        @Override
        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                responseMap.put("headers", response.getAllHeaders());
                //System.out.println("Ratelimit attempts left: " + response.getHeaders("X-RateLimit-Remaining")[0]);
                //System.out.println("Etag = " + response.getHeaders("ETag")[0]);
                return entity != null ? EntityUtils.toString(entity) : null;
            } else if (status == 304) {
                //System.out.println("GOT 304!!!");
                return null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        }

    };
    String responseBody = httpclient.execute(httpget, responseHandler);
    responseMap.put("content", responseBody);
    return responseMap;
}