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.kitodo.data.index.elasticsearch.type.HistoryTypeTest.java

@Test
public void shouldCreateDocument() throws Exception {
    HistoryType historyType = new HistoryType();

    History history = prepareData().get(0);
    HttpEntity document = historyType.createDocument(history);
    String actual = EntityUtils.toString(document);
    //again ordering is not kept but it can be caused by EntityUtils
    String excepted = "{\"date\":\"2017-01-14\",\"numericValue\":\"1.0\",\"stringValue\":\"1\","
            + "\"process\":\"1\",\"type\":\"unknown\"}";
    assertEquals("History JSON string doesn't match to given plain text!", excepted, actual);

    history = prepareData().get(1);/* ww w . ja  v  a 2  s.com*/
    document = historyType.createDocument(history);
    actual = EntityUtils.toString(document);
    //again ordering is not kept but it can be caused by EntityUtils
    excepted = "{\"date\":null,\"numericValue\":\"2.0\",\"stringValue\":\"2\",\"process\":\"2\","
            + "\"type\":\"grayScale\"}";
    assertEquals("History JSON string doesn't match to given plain text!", excepted, actual);
}

From source file:com.example.hbranciforte.trafficclient.History.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_history);
    DefaultHttpClient httpclient = new DefaultHttpClient();
    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    String token = telephonyManager.getDeviceId().toString();
    //HttpPost httppostreq = new HttpPost("http://10.0.2.2:3000/parkings??notification_token=".concat(token));
    ListView listView = (ListView) findViewById(R.id.historyable);

    try {//from w  w w.  java 2s  .  c  o m
        HttpClient client = new DefaultHttpClient();
        String getURL = "http://45.55.79.197/parkings?notification_token=".concat(token);
        //String getURL = "http://10.0.2.2:3000/parkings?notification_token=".concat(token);
        HttpGet get = new HttpGet(getURL);
        HttpResponse responseGet = client.execute(get);
        HttpEntity resEntityGet = responseGet.getEntity();
        if (resEntityGet != null) {
            String response = EntityUtils.toString(resEntityGet);
            data = new JSONArray(response);

            String[] values = new String[data.length()];
            for (int i = 0; i < this.data.length(); i++) {
                JSONObject parking = new JSONObject(data.get(i).toString());
                JSONObject zone = new JSONObject(parking.getString("zone"));
                JSONObject car = new JSONObject(parking.getString("car"));
                String temp = "Patente: ".concat(car.getString("license_plate")).concat("\n");
                temp = temp.concat("Zona: ").concat(zone.getString("name")).concat("-")
                        .concat(Integer.toString(zone.getInt("number")).concat("\n"));
                temp = temp.concat("Estado: ").concat(parking.getString("status")).concat("\n");
                values[i] = temp.concat("Valido hasta: ").concat(parking.getString("formated_expires_at"));

            }
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
                    android.R.id.text1, values);
            listView.setAdapter(adapter);
        }
    } catch (Exception e) {
        Log.e("Error Parsing:", e.getMessage());
    }

}

From source file:io.wcm.maven.plugins.contentpackage.httpaction.PackageManagerHtmlMessageCall.java

@Override
public String execute() throws MojoExecutionException {
    if (log.isDebugEnabled()) {
        log.debug("Call URL: " + method.getURI());
    }// w w w . ja va 2 s. co  m

    try (CloseableHttpResponse response = httpClient.execute(method)) {
        String responseString = EntityUtils.toString(response.getEntity());

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

            // debug output whole xml
            if (log.isDebugEnabled()) {
                log.debug("CRX Package Manager Response:\n" + responseString);
            }

            // remove all HTML tags and special conctent
            final Pattern HTML_STYLE = Pattern.compile("<style[^<>]*>[^<>]*</style>",
                    Pattern.MULTILINE | Pattern.DOTALL);
            final Pattern HTML_JAVASCRIPT = Pattern.compile("<script[^<>]*>[^<>]*</script>",
                    Pattern.MULTILINE | Pattern.DOTALL);
            final Pattern HTML_ANYTAG = Pattern.compile("<[^<>]*>");

            responseString = HTML_STYLE.matcher(responseString).replaceAll("");
            responseString = HTML_JAVASCRIPT.matcher(responseString).replaceAll("");
            responseString = HTML_ANYTAG.matcher(responseString).replaceAll("");
            responseString = StringUtils.replace(responseString, "&nbsp;", " ");

            return responseString;
        } else {
            throw new MojoExecutionException("Failure:\n" + responseString);
        }

    } catch (IOException ex) {
        throw new MojoExecutionException("Http method failed.", ex);
    }
}

From source file:com.aremaitch.codestock2010.datadownloader.ConferenceAgendaDownloader.java

@Override
public JSONObject getSpeakerData() {
    JSONObject result = null;//from w ww  . j a  va  2  s.  c  om

    try {
        ACLogger.info(CSConstants.AGENDADWNLDSVC_LOG_TAG, "downloading speaker data");
        DefaultHttpClient hc = new DefaultHttpClient();
        HttpGet hg = new HttpGet(getSpeakersUrl());
        HttpResponse response = hc.execute(hg);
        result = new JSONObject(EntityUtils.toString(response.getEntity()));
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return result;
}

From source file:org.finra.msl.client.MockAPI.java

/**
 * Register a template that is passed to the web-server where the it is
 * stored using the ID as the key. This is used later when setting up a mock
 * response.//from  ww w  .  j  a  v a  2s.  c  o m
 * 
 * @param server
 *            => url of web-server.js running on node
 * @param port
 *            => port number of web-server.js running on node
 * @param template
 *            => the template that is to be registered for later use
 * @param id
 *            => key used to indicate which template is to be used when
 *            mocking a response
 * @return => returns the response
 * @throws Exception
 */
public static String registerTemplate(String server, int port, String template, String id) throws Exception {
    HttpPost post = null;
    JSONObject object = new JSONObject();

    URIBuilder builder = new URIBuilder();

    builder.setScheme("http").setHost(server).setPort(port).setPath("/mock/template");

    post = new HttpPost(builder.toString());
    object.put("template", template);
    object.put("id", id);

    post.setHeader("Content-Type", "application/json");
    post.setEntity(new StringEntity(object.toString()));

    HttpClient client = new DefaultHttpClient();
    HttpResponse resp = client.execute(post);

    if (resp.getStatusLine().getStatusCode() != 200) {
        throw new Exception("POST failed. Error code: " + resp.getStatusLine().getStatusCode());
    }
    return EntityUtils.toString(resp.getEntity());

}

From source file:synapticloop.b2.request.B2GetUploadPartUrlRequest.java

/**
 * Return the upload url response /*from   ww  w.ja v a2s.co  m*/
 * 
 * @return the upload url response
 * 
 * @throws B2ApiException if something went wrong
 * @throws IOException    if there was an error communicating with the API service
 */
public B2GetUploadPartUrlResponse getResponse() throws B2ApiException, IOException {
    return new B2GetUploadPartUrlResponse(EntityUtils.toString(executePost().getEntity()));
}

From source file:moxy.ProxyHttpAppTest.java

@Test
public void canProxyGetRequests() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet request = new HttpGet("http://localhost:6565/healthcheck");

    CloseableHttpResponse response = httpclient.execute(request);

    try {/*w  w w . j av a  2s .  c om*/
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("{\"deadlocks\":{\"healthy\":true}}", EntityUtils.toString(response.getEntity()));
        assertableListener.assertConnectionWasMadeOn(6565);
    } finally {
        httpclient.close();
    }
}

From source file:com.wichita.edu.crawler.GerritHttpRequest.java

public GerritHttpRequest(String url) throws JSONException

{

    try {/*from  ww  w.j av  a2s.  c  o m*/

        System.out.println(url);
        //sending an httprequest with GET method and get result by httpEntity
        HttpClient httpclient = HttpClientBuilder.create().build();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;
        HttpGet httpGet = new HttpGet(url);
        httpResponse = httpclient.execute(httpGet);
        httpEntity = httpResponse.getEntity();
        String response = EntityUtils.toString(httpEntity);
        System.out.println(response);
        //if response be empty the length of response is 8.
        if (response.length() > 8) {
            //JSON response has )]} extra characters which should be remove.
            response = response.replace(")]}'", "");

            //response from this url:"https://git.eclipse.org/r/changes/?q=mylyn&o=ALL_REVISIONS&o=ALL_FILES&o=MESSAGES";
            if (response.startsWith("\n[")) {
                //declare JSONArray from response 
                reviewDataArray = new JSONArray(response);
                if (reviewDataArray.length() > 1) {
                    //declare JSONObject from reviewDataArray
                    reviewDataObject = reviewDataArray.getJSONObject(1);
                } else {
                    //declare JSONObject from reviewDataArray
                    reviewDataObject = reviewDataArray.getJSONObject(0);
                }

            }
            //response from this url:""https://git.eclipse.org/r/changes/"+entry.getKey()+"/revisions/"+value+"/comments"
            else if (response.startsWith("\n{")) {
                reviewDataObject = new JSONObject(response);
                // System.out.println(response.toString());
            }

        }

    }

    catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:org.elasticsearch.rest.action.main.RestMainActionIT.java

public void testGetRequest() throws IOException {
    try (Response response = getRestClient().performRequest("GET", "/", Collections.emptyMap(), null)) {
        assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
        assertNotNull(response.getEntity());
        assertThat(EntityUtils.toString(response.getEntity()), containsString("cluster_name"));
    }/*from   w  ww.  j av  a  2  s.co  m*/
}

From source file:com.ericsson.gerrit.plugins.syncindex.IndexResponseHandler.java

private String parseResponse(HttpResponse response) {
    HttpEntity entity = response.getEntity();
    String asString = "";
    if (entity != null) {
        try {//  ww  w.  ja v  a 2  s . c om
            asString = EntityUtils.toString(entity);
        } catch (IOException e) {
            log.error("Error parsing entity", e);
        }
    }
    return asString;
}