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:web.restful.ClientTest.java

public static void main(String[] args) throws ClientProtocolException, IOException {
    HttpClient client = new DefaultHttpClient();
    HttpPut put = new HttpPut("http://localhost:8080/ss16-lab-web/resources/outliers/session");
    put.setEntity(new StringEntity("upenkwbq"));// session ID
    client.execute(put);/* w  ww.  java  2 s  . co  m*/
    put.releaseConnection();

    put = new HttpPut("http://localhost:8080/ss16-lab-web/resources/outliers/bucket");
    put.setEntity(new StringEntity("Level1/Level1_Bin_1.txt")); // bucket name
    client.execute(put);
    put.releaseConnection();

    put = new HttpPut("http://localhost:8080/ss16-lab-web/resources/outliers/method");
    put.setEntity(new StringEntity("chauvenet")); // method name
    client.execute(put);
    put.releaseConnection();

    HttpGet get = new HttpGet("http://localhost:8080/ss16-lab-web/resources/outliers");
    HttpResponse response = client.execute(get);
    HttpEntity en = response.getEntity();
    InputStreamReader i = new InputStreamReader(en.getContent());
    BufferedReader rd = new BufferedReader(i);
    String line = "";
    while ((line = rd.readLine()) != null) {
        System.out.println(line);
    }
}

From source file:TestRESTPost12.java

public static void main(String[] p) throws Exception {
    String strurl = "http://localhost:8080/testnewmaven8/webresources/service/post";

    //StringEntity str=new StringEntity("<a>hello post</a>",ContentType.create("application/xml" , Consts.UTF_8));

    ////from   ww w .jav  a 2 s. c o m
    StringEntity str = new StringEntity("hello post");
    str.setContentType("APPLICATION/xml");

    CloseableHttpClient httpclient = HttpClients.createDefault();

    HttpPost httppost = new HttpPost(strurl);
    httppost.addHeader("Accept", "application/xml charset=UTF-8");
    //httppost.addHeader("content_type", "application/xml, multipart/related");
    httppost.setEntity(str);

    CloseableHttpResponse response = httpclient.execute(httppost);
    // try
    //{
    int statuscode = response.getStatusLine().getStatusCode();
    if (statuscode != 200) {
        System.out.println("http error occured=" + statuscode);
    }

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

    while (br.readLine() != null) {
        System.out.println(br.readLine());
    }
    // }
    /*catch(Exception e)
    {
        System.out.println("exception :"+e);
    }*/

    //httpclient.close();

}

From source file:RestPostClient.java

public static void main(String[] args) throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost("http://localhost:10080/example/json/product/post");

    StringEntity input = new StringEntity("{\"qty\":100,\"name\":\"iPad 4\"}");
    input.setContentType("application/json");
    postRequest.setEntity(input);//www .  j a v  a  2 s  .c o  m

    HttpResponse response = httpClient.execute(postRequest);

    //if (response.getStatusLine().getStatusCode() != 201) {
    //   throw new RuntimeException("Failed : HTTP error code : "
    //      + 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:chat.parse.ChatParse.java

/**
 * @param args the command line arguments
 *//* ww  w .j  av a2 s .c o m*/
public static void main(String[] args) throws JSONException, IOException {

    String url = "https://api.parse.com/1/classes/";
    String applicationkey = "RfIUZYQki1tKxFhciTxjD4a712gy1SeY9sw7hhbO";
    String RestApiKey = "WjlZA2VIuonVgd6FKac6tpO8LGztARUHUKFEmeTi";

    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url + "contatti");

    post.addHeader("Content-Type", "application/json");
    post.addHeader("X-Parse-Application-Id", applicationkey);
    post.addHeader("X-Parse-REST-API-Key", RestApiKey);

    JSONObject obj = new JSONObject();
    obj.put("nome", "Paolo");
    obj.put("surname", "Possanzini");
    obj.put("email", "paolo@teamdev.it");

    post.setEntity(new StringEntity(obj.toString()));

    client.execute(post);

}

From source file:hackathon.Hackathon.java

/**
 * @param args the command line arguments
 *//*from  w w  w  . ja va 2s  . com*/
public static void main(String[] args) {
    // TODO code application logic here
    HttpClient httpclient = HttpClients.createDefault();

    try {
        URIBuilder builder = new URIBuilder(
                "https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize");

        URI uri = builder.build();
        HttpPost request = new HttpPost(uri);
        request.setHeader("Content-Type", "application/json");
        request.setHeader("Ocp-Apim-Subscription-Key", "3532e4ff429c4cce9baa783451db8b3b");

        // Request body
        String url = "https://s-media-cache-ak0.pinimg.com/564x/af/8b/47/af8b47d56ded6952fa8ebfdcf7e87f43.jpg";
        StringEntity reqEntity = new StringEntity(
                "{'url' : 'https://s-media-cache-ak0.pinimg.com/564x/af/8b/47/af8b47d56ded6952fa8ebfdcf7e87f43.jpg'}");
        request.setEntity(reqEntity);

        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            System.out.println(EntityUtils.toString(entity));
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

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

public static void main(String[] args) throws UnsupportedEncodingException {
    /**/*from www  .ja v  a 2s  .  co m*/
     * Amazon ElasticSearch Service URL:
     * endpoint + / + {index_name} + / + {type} + / + {id}
     */
    String elastic_search_url = "http://xxxxx-yyyyy-r6nvlhpscgdwms5.ap-northeast-1.es.amazonaws.com/inventory/simple/123";

    /* Record to add in elastic search */
    String jsonDocument = "{\"id\": \"123\", \"name\": \"Apple iPhone 6s\", \"stock\" : 10}";

    /* Convert jsonDocument to apache StringEntity */
    StringEntity payload = new StringEntity(jsonDocument);

    /* Prepare post request to add record */
    HttpPost httpPost = new HttpPost(elastic_search_url);
    /* Attach payload */
    httpPost.setEntity(payload);
    /* Execute post request */
    httpPostRequest(httpPost);
}

From source file:com.direct.PortalCheckDirect.java

public static void main(String[] args) throws IOException, JSONException {

    //This API is for Direct Business
    final String apiEndPoint = "https://secure.policecheckexpress.com.au/pce/api/portalCheckDirect/new";
    final String apiToken = "secure Token";
    try {//from  w  w  w  .ja v  a2s. c  o m

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(apiEndPoint);

        //filling Portal Check with Sample Data
        DirectPortalCheck directPortalCheck = fillSampleData();
        String parameters = fillParameters(directPortalCheck, apiToken);
        StringEntity input = new StringEntity(parameters);
        input.setContentType("application/json");
        postRequest.setEntity(input);
        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String jsonText = readAll(br);
        JSONArray json = new JSONArray("[" + jsonText + "]");
        JSONObject obj = (JSONObject) json.get(0);
        if (!(Boolean) obj.get("error")) {

            System.out.println(obj.get("message"));
            System.out.println("Invitation Id = " + obj.get("id"));
        } else {
            System.out.println("++++++++++++++++++++++++++");
            System.out.println("Error  = " + obj.get("message"));
            System.out.println("++++++++++++++++++++++++++");

        }

        httpClient.getConnectionManager().shutdown();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

}

From source file:com.sme.SmePoliceCheck.java

public static void main(String[] args) throws IOException, JSONException {

    // This API is for SME
    // After creating Police Check you should Upload documents and then submit the police check
    // 1-Create Police Check
    // 2-Upload Documents for Police Check ID
    // 3-Submit Police Check to Intercheck

    final String apiEndPoint = "https://secure.policecheckexpress.com.au/pce/api/portalCheckSme/new";
    final String apiToken = "secure token";
    try {/* w ww . j a va2s . c  o  m*/

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(apiEndPoint);

        //filling Portal Check with sample Data

        SmePortalCheck smePortalCheck = fillSampleData();
        String parameters = fillParameters(smePortalCheck, apiToken);
        StringEntity input = new StringEntity(parameters);
        input.setContentType("application/json");
        postRequest.setEntity(input);
        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        String jsonText = readAll(br);
        JSONArray json = new JSONArray("[" + jsonText + "]");
        JSONObject obj = (JSONObject) json.get(0);
        if (!(Boolean) obj.get("error")) {

            System.out.println(obj.get("message"));
            System.out.println("Invitation Id = " + obj.get("id"));
        } else {
            System.out.println("++++++++++++++++++++++++++");
            System.out.println("Error  = " + obj.get("message"));
            System.out.println("++++++++++++++++++++++++++");
        }

        httpClient.getConnectionManager().shutdown();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

}

From source file:com.gemini.httpclienttest.HttpClientTestMain.java

public static void main(String[] args) {
    //authenticate with the server
    URL url;/*from  w  w  w  . j  a  va 2 s .  c o  m*/
    try {
        url = new URL("http://198.11.209.34:5000/v2.0/tokens");
    } catch (MalformedURLException ex) {
        System.out.printf("Invalid Endpoint - not a valid URL {}", "http://198.11.209.34:5000/v2.0");
        return;
    }
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
    try {
        HttpPost httpPost = new HttpPost(url.toString());
        httpPost.setHeader("Content-Type", "application/json");
        StringEntity strEntity = new StringEntity(
                "{\"auth\":{\"tenantName\":\"Gemini-network-prj\",\"passwordCredentials\":{\"username\":\"sri\",\"password\":\"srikumar12\"}}}");
        httpPost.setEntity(strEntity);
        //System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpPost);
        try {
            //get the response status code 
            String respStatus = response.getStatusLine().getReasonPhrase();

            //get the response body
            int bytes = response.getEntity().getContent().available();
            InputStream body = response.getEntity().getContent();
            BufferedReader in = new BufferedReader(new InputStreamReader(body));
            String line;
            StringBuffer sbJSON = new StringBuffer();
            while ((line = in.readLine()) != null) {
                sbJSON.append(line);
            }
            String json = sbJSON.toString();
            EntityUtils.consume(response.getEntity());

            GsonBuilder gsonBuilder = new GsonBuilder();
            Object parsedJson = gsonBuilder.create().fromJson(json, Object.class);
            System.out.printf("Parsed json is of type %s\n\n", parsedJson.getClass().toString());
            if (parsedJson instanceof com.google.gson.internal.LinkedTreeMap) {
                com.google.gson.internal.LinkedTreeMap treeJson = (com.google.gson.internal.LinkedTreeMap) parsedJson;
                if (treeJson.containsKey("id")) {
                    String s = (String) treeJson.getOrDefault("id", "no key provided");
                    System.out.printf("\n\ntree contained id %s\n", s);
                } else {
                    System.out.printf("\n\ntree does not contain key id\n");
                }
            }
        } catch (IOException ex) {
            System.out.print(ex);
        } finally {
            response.close();
        }
    } catch (IOException ex) {
        System.out.print(ex);
    } finally {
        //lots of exceptions, just the connection and exit
        try {
            httpclient.close();
        } catch (IOException | NoSuchMethodError ex) {
            System.out.print(ex);
            return;
        }
    }
}

From source file:org.kuali.kfs.rest.AccountingPeriodCloseJob.java

public static void main(String[] args) {
    try {//  ww w .  j  av a  2 s.c o m
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost request = new HttpPost("http://localhost:8080/kfs-dev/coa/accounting_periods/close");
        request.addHeader("accept", "application/json");
        request.addHeader("content-type", "application/json");
        request.addHeader("authorization", "NSA_this_is_for_you");

        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append("\"description\":\"Document: The Next Generation\",");
        sb.append("\"universityFiscalYear\": 2016,");
        sb.append("\"universityFiscalPeriodCode\": \"03\"");
        sb.append("}");
        StringEntity data = new StringEntity(sb.toString());
        request.setEntity(data);

        HttpResponse response = httpClient.execute(request);

        System.out.println("Status Code: " + response.getStatusLine().getStatusCode());
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + 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();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}