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:ch.iterate.openstack.swift.Response.java

/**
 * Returns the response body as text//from w ww  .j  a  v  a  2  s . com
 *
 * @return The response body
 * @throws IOException If an error occurs reading the input stream
 */
public String getResponseBodyAsString() throws IOException {
    return EntityUtils.toString(response.getEntity());
}

From source file:pingdesktop.Model.HttpHandler.java

public static String doPost(List<NameValuePair> nvps, String target_url) throws IOException {

    /* create the HTTP client and POST request */
    HttpPost httpPost = new HttpPost(BaseUrl + target_url);

    /* add some request parameters for a form request */
    //        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    ///*from   w  ww .  j a va  2  s .  co m*/
    //        nvps.add(new BasicNameValuePair("username", "pangeranweb"));
    //        nvps.add(new BasicNameValuePair("password", "anisnuzulan"));
    nvps.add(new BasicNameValuePair("Content-Type", "application/x-www-form-urlencoded"));
    httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    /* execute request */
    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();

    /* process response */
    if (httpResponse.getStatusLine().getStatusCode() == 200) {
        String responseText = EntityUtils.toString(httpEntity);
        return responseText;
    } else {
        return "Invalid HTTP response: " + httpResponse.getStatusLine().getStatusCode();
    }

}

From source file:com.wbtech.dao.NetworkUitlity.java

public static MyMessage post(String url, String data) {
    // TODO Auto-generated method stub
    String returnContent = "";
    MyMessage message = new MyMessage();
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    try {/*from   w w w  .  j ava 2  s .  co  m*/
        StringEntity se = new StringEntity("content=" + data, HTTP.UTF_8);
        Log.d("postdata", "content=" + data);
        se.setContentType("application/x-www-form-urlencoded");
        httppost.setEntity(se);
        HttpResponse response = httpclient.execute(httppost);
        int status = response.getStatusLine().getStatusCode();

        String returnXML = EntityUtils.toString(response.getEntity());
        returnContent = URLDecoder.decode(returnXML);
        switch (status) {
        case 200:
            message.setFlag(true);
            message.setMsg(returnContent);
            break;

        default:
            Log.e("error", status + returnContent);
            message.setFlag(false);
            message.setMsg(returnContent);
            break;
        }
    } catch (Exception e) {
        JSONObject jsonObject = new JSONObject();

        if (e.getMessage().equalsIgnoreCase("no route to host")) {
            try {
                jsonObject.put("err", "??,???");
                returnContent = jsonObject.toString();
                message.setFlag(false);
                message.setMsg(returnContent);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        }

        else if (e.getMessage().equalsIgnoreCase("network unreachable")
                || e.getMessage().equalsIgnoreCase("www.cobub.com")) {
            try {
                jsonObject.put("err", "");
                returnContent = jsonObject.toString();
                message.setFlag(false);
                message.setMsg(returnContent);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        }

        else {
            try {
                jsonObject.put("err", "");
                returnContent = jsonObject.toString();
                message.setFlag(false);
                message.setMsg(returnContent);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        }

    }
    return message;
}

From source file:com.cloud.utils.rest.HttpRequestMatcher.java

private static String getPayload(final HttpRequest request) {
    String payload = "";
    if (request instanceof HttpEntityEnclosingRequest) {
        try {/* w w  w.  j a va2  s.  co m*/
            payload = EntityUtils.toString(((HttpEntityEnclosingRequest) request).getEntity());
        } catch (final ParseException e) {
            throw new IllegalArgumentException("Couldn't read request's entity payload.", e);
        } catch (final IOException e) {
            throw new IllegalArgumentException("Couldn't read request's entity payload.", e);
        }
    }
    return payload;
}

From source file:tisseows.RequestTisseo.java

/**
 * Envoi une requte au WS Tisso et rcupre la rponse
 * @return/*from   ww  w .  j a va  2  s  .  c om*/
 * @throws IOException
 * @throws URISyntaxException 
 */
public String request() throws IOException, URISyntaxException {
    this.urib.setParameter("key", "a03561f2fd10641d96fb8188d209414d8");
    this.urib.setParameter("format", "json");
    URI uri = urib.build();

    String s = "";
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet(uri);
    try (CloseableHttpResponse response = httpclient.execute(httpget)) {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            s = EntityUtils.toString(entity);
        }
    }
    return s;
}

From source file:com.mmj.app.common.util.SpiderHtmlUtils.java

/**
 * ?URLhtml?/*from   ww w. j  ava  2s .c o  m*/
 * 
 * @param url
 * @return
 */
public static String getHtmlByUrl(String url) {
    if (StringUtils.isEmpty(url)) {
        return null;
    }
    String html = null;
    HttpClient httpClient = new DefaultHttpClient();// httpClient
    HttpUriRequest httpget = new HttpGet(url);// get?URL
    httpget.setHeader("Connection", "keep-alive");
    httpget.setHeader("Referer", "http://www.baidu.com");
    httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    httpget.setHeader("User-Agent",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36");
    try {
        HttpResponse responce = httpClient.execute(httpget);// responce
        int responseCode = responce.getStatusLine().getStatusCode();// ?
        if (responseCode == HttpStatus.SC_OK || responseCode == HttpStatus.SC_MOVED_PERMANENTLY
                || responseCode == HttpStatus.SC_MOVED_TEMPORARILY) {// 200 ?
            // 
            HttpEntity entity = responce.getEntity();
            if (entity != null) {
                html = EntityUtils.toString((org.apache.http.HttpEntity) entity);// html??
            }
        }
    } catch (Exception e) {
        logger.error("SpiderHtmlUtils:getHtmlByUrl sprider url={} error!!!", url);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return html;
}

From source file:com.kingmed.dp.ndp.NDPConnectionManager.java

@Override
public void connect() throws Exception {
    String signinUrl = ndpServe.getUrlSignin();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*  w w w.  j  av a2 s .  c  o m*/
        HttpGet httpget = new HttpGet(signinUrl);
        String responseBody = httpclient.execute(httpget, new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse hr) throws ClientProtocolException, IOException {
                int status = hr.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = hr.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }

        });
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        httpclient.close();
    }
}

From source file:kn.uni.gis.foxhunt.context.GameContext.java

/**
 * creates a new fox game/*  w  w  w  .  jav  a  2 s  . c  om*/
 * 
 * @param id
 * @param playerName
 */
public static void newFoxGame(String playerName) throws GameException {

    final AtomicReference<String> ref = new AtomicReference<String>();
    final AtomicReference<Exception> exc = new AtomicReference<Exception>();
    HttpContext.getInstance().put(SettingsContext.getInstance().getServerUrl(), null,
            new EntityHandlerAdapter() {
                @Override
                public void handleEntity(HttpEntity entity, int statusCode) {
                    if (statusCode == HttpStatus.SC_OK) {
                        try {
                            ref.set(EntityUtils.toString(entity));

                        } catch (ParseException e) {
                            exc.set(e);
                        } catch (IOException e) {
                            exc.set(e);
                        }
                    } else {
                        exc.set(new GameException("bad status code: " + statusCode));
                    }
                }

                @Override
                public void handleException(Exception exception) {
                    exc.set(exception);
                }
            });

    if (ref.get() == null) {
        throw exc.get() != null ? new GameException(exc.get())
                : new GameException("unrecognized error code from server");
    }
    currentGame = new Game(ref.get(), playerName, Util.createFoxUrl(ref.get()), Util.createGameUrl(ref.get()));
}

From source file:tisseows.RequestJCDecaux.java

/**
 * Envoi une requte au WS JCDecaux et rcupre la rponse
 * @return/*from w  ww. j  av  a 2 s.  co  m*/
 * @throws IOException
 * @throws URISyntaxException 
 */
public String request() throws IOException, URISyntaxException {
    this.urib.setParameter("apiKey", "540dadb9d69e046c2fb68ace08faa0508ed59db7");
    this.urib.setParameter("contract", "Toulouse");
    URI uri = urib.build();

    String s = "";
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet(uri);
    try (CloseableHttpResponse response = httpclient.execute(httpget)) {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            s = EntityUtils.toString(entity);
        }
    }
    return s;
}

From source file:org.keycloak.testsuite.saml.AuthnRequestTest.java

@Test
public void testIsPassiveNotSet() throws Exception {
    String res = new SamlClientBuilder().authnRequest(getAuthServerSamlEndpoint(REALM_NAME),
            SAML_CLIENT_ID_SALES_POST, SAML_ASSERTION_CONSUMER_URL_SALES_POST, Binding.POST)
            .transformObject(so -> {/*from   w  ww. ja v  a 2s.  c o  m*/
                so.setIsPassive(null);
                return so;
            }).build()

            .executeAndTransform(resp -> EntityUtils.toString(resp.getEntity()));

    assertThat(res, containsString("login"));
}