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:com.srotya.tau.ui.BapiLoginDAO.java

public static Entry<String, String> authenticate(String authURL, String username, String password)
        throws Exception {
    CloseableHttpClient client = Utils.buildClient(authURL, 3000, 5000);
    HttpPost authRequest = new HttpPost(authURL);
    Gson gson = new Gson();
    JsonObject obj = new JsonObject();
    obj.addProperty(USERNAME, username);
    obj.addProperty(PASSWORD, password);
    StringEntity entity = new StringEntity(gson.toJson(obj), ContentType.APPLICATION_JSON);
    authRequest.setEntity(entity);/*from w ww  .j a va  2 s . c o  m*/
    CloseableHttpResponse response = client.execute(authRequest);
    if (response.getStatusLine().getStatusCode() == 200) {
        String tokenPair = EntityUtils.toString(response.getEntity());
        JsonArray ary = gson.fromJson(tokenPair, JsonArray.class);
        obj = ary.get(0).getAsJsonObject();
        String token = obj.get(X_SUBJECT_TOKEN).getAsString();
        String hmac = obj.get(HMAC).getAsString();
        return new AbstractMap.SimpleEntry<String, String>(token, hmac);
    } else {
        System.err.println("Login failed:" + response.getStatusLine().getStatusCode() + "\t"
                + response.getStatusLine().getReasonPhrase());
        return null;
    }
}

From source file:org.megam.api.http.TransportResponse.java

public TransportResponse(StatusLine tempStatus, HttpEntity tempEntity, Locale tempLocale)
        throws ParseException, IOException {
    entity = EntityUtils.toString(tempEntity);
    status = tempStatus.toString();/*from   w w  w.j a v  a  2 s .com*/
    locale = tempLocale.getDisplayCountry() + ":" + tempLocale.getDisplayLanguage();
}

From source file:com.javaquery.aws.elasticsearch.DeleteExample.java

/**
 * Perform delete request.//www.j a  v  a  2s  .  c o m
 * @param httpDelete
 */
public static void httpDeleteRequest(HttpDelete httpDelete) {
    /* Create object of CloseableHttpClient */
    CloseableHttpClient httpClient = HttpClients.createDefault();

    /* Response handler for after request execution */
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        @Override
        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            /* Get status code */
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                /* Convert response to String */
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        }
    };

    try {
        /* Execute URL and attach after execution response handler */
        String strResponse = httpClient.execute(httpDelete, responseHandler);
        /* Print the response */
        System.out.println("Response: " + strResponse);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:dk.kk.ibikecphlib.search.HTTPAutocompleteHandler.java

@SuppressLint("NewApi")

public static JsonNode performGET(String urlString) {
    JsonNode ret = null;//  w  ww .  j  a va  2s .  co m

    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, 20000);
    HttpConnectionParams.setSoTimeout(myParams, 20000);
    HttpClient httpclient = new DefaultHttpClient(myParams);
    HttpGet httpget = null;

    URL url = null;

    try {

        url = new URL(urlString);
        httpget = new HttpGet(url.toString());
        LOG.d("Request " + url.toString());
        httpget.setHeader("Content-type", "application/json");
        HttpResponse response = httpclient.execute(httpget);
        String serverResponse = EntityUtils.toString(response.getEntity());
        LOG.d("Response " + serverResponse);
        ret = Util.stringToJsonNode(serverResponse);

    } catch (Exception e) {
        if (e != null && e.getLocalizedMessage() != null)
            LOG.e(e.getLocalizedMessage());
    }
    return ret;
}

From source file:email.mandrill.MandrillApiHandler.java

public static Map<String, Object> getEmailDetails(String mandrillEmailId)
        throws URISyntaxException, IOException {
    Map<String, Object> emailDetails = new HashMap<>();
    HttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet("https://mandrillapp.com/api/1.0/messages/info.json");
    URI uri = new URIBuilder(httpGet.getURI()).addParameter("key", SendEmail.MANDRILL_KEY)
            .addParameter("id", mandrillEmailId).build();
    logger.info("Getting Email details: " + uri.toString());
    Gson gson = new Gson();
    httpGet.setURI(uri);/*from w ww.j  ava2  s  .c om*/

    //Execute and get the response.
    HttpResponse response = httpclient.execute(httpGet);
    HttpEntity responseEntity = response.getEntity();
    if (responseEntity != null) {
        String jsonContent = EntityUtils.toString(responseEntity);
        logger.info(jsonContent);
        // Create a Reader from String
        Reader stringReader = new StringReader(jsonContent);

        // Pass the string reader to JsonReader constructor
        JsonReader reader = new JsonReader(stringReader);
        reader.setLenient(true);
        Map<String, Object> mandrillEmailDetails = gson.fromJson(reader, Map.class);
        emailDetails.put("sent_on", mandrillEmailDetails.get("ts"));
        emailDetails.put("mandrill_id", mandrillEmailDetails.get("_id"));
        emailDetails.put("email_state", mandrillEmailDetails.get("state"));
        emailDetails.put("subject", mandrillEmailDetails.get("subject"));
        emailDetails.put("email", mandrillEmailDetails.get("email"));
        emailDetails.put("tags", mandrillEmailDetails.get("tags"));
        emailDetails.put("opens", mandrillEmailDetails.get("opens"));
        emailDetails.put("clicks", mandrillEmailDetails.get("clicks"));
        emailDetails.put("sender", mandrillEmailDetails.get("sender"));

    }

    return emailDetails;
}

From source file:com.eincs.athens.android.utils.JSONResponseHandler.java

@Override
public JSONObject handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
    StringBuffer sb = new StringBuffer();
    sb.append(EntityUtils.toString(response.getEntity()));
    try {//from  ww w  .j  av  a 2  s. c o m
        return new JSONObject(sb.toString());
    } catch (Exception e) {
        return null;
    }
}

From source file:co.cask.cdap.gateway.handlers.PingHandlerTest.java

@Test
public void testPing() throws Exception {
    HttpResponse response = GatewayFastTestsSuite.doGet("/ping");
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    Assert.assertEquals("OK.\n", EntityUtils.toString(response.getEntity()));
}

From source file:com.kingmed.dp.aperio.DsClient.java

public static String logon() throws Exception {
    String token = null;/*  w ww  .  j av a2s. c o m*/
    String url = "http://192.168.180.132:86/Aperio.Security/Security2.asmx";
    String body = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns=\"http://www.aperio.com/webservices/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"> <SOAP-ENV:Body> <Logon><Token>leQJYfWQ6wv_tJa6hhBZlWwgrRZ-mDywnfb9F4EfC1752Pt07NZDEGvFNYYPvpxkN0IvPTrPi0M=</Token><LoginName>gzuser</LoginName><Password>gzking</Password></Logon></SOAP-ENV:Body> </SOAP-ENV:Envelope> ";

    HttpClient hc = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    httpPost.addHeader("Content-Type", "text/xml;charset=utf-8");
    httpPost.addHeader("SOAPAction", "http://www.aperio.com/webservices/#Logon");
    StringEntity myEntity = new StringEntity(body, ContentType.create("text/xml", "UTF-8"));
    httpPost.setEntity(myEntity);
    System.out.println(myEntity.getContentType());
    System.out.println("Content-Length" + myEntity.getContentLength());
    HttpResponse res = null;
    res = (CloseableHttpResponse) hc.execute(httpPost);
    HttpEntity entity = res.getEntity();
    System.out.println(EntityUtils.toString(entity));

    return token;
}

From source file:com.ericsson.gerrit.plugins.highavailability.forwarder.rest.HttpResponseHandler.java

private static String parseResponse(HttpResponse response) {
    HttpEntity entity = response.getEntity();
    String asString = "";
    if (entity != null) {
        try {/*from  ww  w  . j  av  a 2s.co m*/
            asString = EntityUtils.toString(entity);
        } catch (IOException e) {
            log.error("Error parsing entity", e);
        }
    }
    return asString;
}

From source file:net.locosoft.fold.neo4j.internal.Neo4jRestUtil.java

public static JsonObject doPostJson(String uri, JsonObject content) {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        HttpPost httpPost = new HttpPost(uri);
        httpPost.addHeader("Content-Type", "application/json");
        StringEntity stringEntity = new StringEntity(content.toString(), "UTF-8");
        httpPost.setEntity(stringEntity);
        CloseableHttpResponse response = httpClient.execute(httpPost);

        String bodyText = EntityUtils.toString(response.getEntity());
        JsonObject jsonObject = JsonObject.readFrom(bodyText);
        return jsonObject;
    } catch (Exception ex) {
        ex.printStackTrace();/*from  ww w.  j  a v  a 2s  .c om*/
    }
    return null;
}