Example usage for org.apache.http.entity StringEntity StringEntity

List of usage examples for org.apache.http.entity StringEntity StringEntity

Introduction

In this page you can find the example usage for org.apache.http.entity StringEntity StringEntity.

Prototype

public StringEntity(String str) throws UnsupportedEncodingException 

Source Link

Usage

From source file:io.tourniquet.junit.http.rules.examples.HttpClientHelper.java

public static HttpPost post(String url, String content) throws UnsupportedEncodingException {

    HttpPost post = new HttpPost(url);
    post.setEntity(new StringEntity(content));
    return post;/*from w w  w  . j a va2s.com*/
}

From source file:com.android.feedmeandroid.HTTPClient.java

public static ArrayList<JSONObject> SendHttpPost(String URL, JSONObject jsonObjSend) {

    try {/*  w  w w. j ava  2  s .  c o  m*/
        ArrayList<JSONObject> retArray = new ArrayList<JSONObject>();
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accepts", "application/json");
        httpPostRequest.setHeader("Content-Type", "application/json");
        // httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set
        // this parameter if you would like to use gzip compression

        long t = System.currentTimeMillis();
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.v(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]");

        // Get hold of the response entity (-> the data):
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            // convert content stream to a String
            String resultString = convertStreamToString(instream);
            Log.i(TAG, resultString);
            instream.close();
            resultString = resultString.substring(1, resultString.length() - 2); // remove wrapping "[" and
            // "]"
            String[] results = resultString.split("\\},\\{");
            for (int i = 0; i < results.length; i++) {
                JSONObject jsonObjRecv;
                String res = results[i];

                // Transform the String into a JSONObject
                if (i == 0 && results.length > 1) {
                    jsonObjRecv = new JSONObject(res + "}");
                } else if (i == results.length - 1 && results.length > 1) {
                    jsonObjRecv = new JSONObject("{" + res);
                } else {
                    jsonObjRecv = new JSONObject("{" + res + "}");
                }
                retArray.add(jsonObjRecv);

                // Raw DEBUG output of our received JSON object:
                Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");
            }

            return retArray;
        }

    } catch (Exception e) {
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    return null;
}

From source file:com.jts.main.helper.Http.java

public static String sendPost(String url, URLParameter param) {
    String retval = "";
    HttpClient httpClient = new DefaultHttpClient();
    try {//from   w  ww.  ja va  2  s .  c  om
        HttpPost request = new HttpPost(My.base_url + url);
        StringEntity params = new StringEntity(param.get());
        request.addHeader("content-type", "application/x-www-form-urlencoded");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);
        // handle response here...
        retval = org.apache.http.util.EntityUtils.toString(response.getEntity());
        org.apache.http.util.EntityUtils.consume(response.getEntity());
    } catch (IOException | ParseException ex) {
        errMsg = ex.getMessage();
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return retval;
}

From source file:es.ucm.look.data.remote.restful.RestMethod.java

/**
 * Used to insert an element/*from   w ww. j  a v  a2  s .co m*/
 * 
 * @param url
 *       Element URI
 * @param c
 *       The element represented with a JSON
 * @return
 *       The response
 */
public static HttpResponse doPost(String url, JSONObject c) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost request = new HttpPost(url);
    StringEntity s = null;
    try {
        s = new StringEntity(c.toString());
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    s.setContentEncoding("UTF-8");
    s.setContentType("application/json");

    request.setEntity(s);
    request.addHeader("accept", "application/json");

    try {
        return httpclient.execute(request);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:webrequester.CouchDBWebRequest.java

public String requestWithPut(String content) {
    String s = "";
    try {//from  w  w w.j a va 2 s  . c om

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPut httpput = new HttpPut(buildURI().toString());

        StringEntity se = new StringEntity(content);
        httpput.setEntity(se);

        CloseableHttpResponse response = httpclient.execute(httpput);
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                s = EntityUtils.toString(entity, "UTF-8");
            }
        } finally {
            response.close();
        }
    } catch (IOException ex) {
        return null;
    }
    return s;
}

From source file:middleware.HTTPRequest.java

public static void doPostVuelo(String jsonRequest) throws UnsupportedEncodingException, IOException {
    String url = "http://localhost:8084/MVIv2/webapi/vuelos";
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(url);
    StringEntity input = new StringEntity(jsonRequest);
    input.setContentType("application/json");
    postRequest.setEntity(input);/*from  ww w .java 2s  .  c  o  m*/

    HttpResponse response = httpClient.execute(postRequest);

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new RuntimeException("ERROR AL INSERTAR DEL TIPO: " + response.getStatusLine().getStatusCode());
    }

    BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }

    httpClient.getConnectionManager().shutdown();

}

From source file:com.tedx.webservices.WebServices.java

public static JSONArray SendHttpPostArray(String URL, JSONObject jsonObjSend) {
    try {/*from w  w w.  ja  v a 2s  .c  om*/
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        //httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression

        long t = System.currentTimeMillis();
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]");

        // Get hold of the response entity (-> the data):
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            // convert content stream to a String
            String resultString = convertStreamToString(instream);
            instream.close();

            // Transform the String into a JSONObject
            JSONArray jsonObjRecv = new JSONArray(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG, "<jsonobject>\n" + jsonObjRecv.toString() + "\n</jsonobject>");

            return jsonObjRecv;
        }
    } catch (Exception e) {
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    return null;
}

From source file:com.flipkart.foxtrot.client.handlers.DummyDocRequestHandler.java

@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context)
        throws HttpException, IOException {
    response.setEntity(new StringEntity(
            "{ \"members\":[{\n" + "    \"host\": \"blah\",\n" + "    \"port\": 80\n" + "}]}"));
    response.setStatusCode(200);//www .  j  ava 2  s  .c  om
}

From source file:org.sharetask.data.IntegrationTest.java

@BeforeClass
public static void login() throws Exception {
    final DefaultHttpClient client = new DefaultHttpClient();
    final HttpPost httpPost = new HttpPost(BASE_URL + "/user/login");
    httpPost.addHeader(new BasicHeader("Content-Type", "application/json"));
    final StringEntity httpEntity = new StringEntity(
            "{\"username\":\"dev1@shareta.sk\"," + "\"password\":\"password\"}");
    System.out.println(EntityUtils.toString(httpEntity));
    httpPost.setEntity(httpEntity);/* w  ww  .j  a  v a2  s. c o m*/

    //when
    final HttpResponse response = client.execute(httpPost);

    //then
    Assert.assertEquals(HttpStatus.OK.value(), response.getStatusLine().getStatusCode());
    client.getCookieStore().getCookies();
    for (final Cookie cookie : client.getCookieStore().getCookies()) {
        if (cookie.getName().equals("JSESSIONID")) {
            DOMAIN = cookie.getDomain();
            SESSIONID = cookie.getValue();
        }
    }
}

From source file:kcb.billerengine.processors.CallJSON.java

private String getJson(HttpClient httpClient, String jsonURL, String body) {
    String sb = null;/* www.  j  a v a2 s .  c  o m*/
    try {
        System.out.println("JSON REQUEST: " + body);
        StringEntity params = new StringEntity(body);

        HttpPost request = new HttpPost(jsonURL);
        request.addHeader("content-type", "application/text");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);

        sb = EntityUtils.toString(response.getEntity(), "UTF-8");

    } catch (IOException | ParseException e) {
        e.printStackTrace();
    }
    System.out.println("ECITIZEN RESPONSE : " + sb);
    httpClient.getConnectionManager().shutdown();
    return sb;
}