Example usage for org.apache.http.client.methods HttpPost HttpPost

List of usage examples for org.apache.http.client.methods HttpPost HttpPost

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpPost HttpPost.

Prototype

public HttpPost(final String uri) 

Source Link

Usage

From source file:postenergy.PostHttpClient.java

public static void main(String[] args) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://iplant.dk/addData.php?n=mindass");

    try {/*from ww  w . java2s .  c  o m*/

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("?n", "=mindass"));

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        String line = "";
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
            if (line.startsWith("Input:")) {
                String key = line.substring(6);
                // do something with the key
                System.out.println("key:" + key);
            }

        }
    } catch (IOException e) {
        System.out.println("There was an error: " + e);
    }
}

From source file:App.App.java

public static void main(String[] args) throws IOException {
    File inFile = new File("C:\\Data\\LogTest.java");
    FileInputStream fis = new FileInputStream(inFile);
    DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
    HttpPost httppost = new HttpPost("http://localhost:8080/rest_j2ee/rest/files/upload");
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("file", new InputStreamBody(fis, inFile.getName()));
    httppost.setEntity(entity);//from w  w w  .  java  2s.  co  m
    HttpResponse response = httpclient.execute(httppost);
    int statusCode = response.getStatusLine().getStatusCode();
    HttpEntity responseEntity = response.getEntity();
    String responseString = EntityUtils.toString(responseEntity, "UTF-8");
    System.out.println("[" + statusCode + "] " + responseString);
}

From source file:org.dineth.shooter.client.Example.java

public static void main(String[] args) {

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost:8080/upload");
    filename = "router.jpg";

    FileBody bin = new FileBody(new File(filename));
    StringBody fileName = null;/*from w  w  w.j  ava2s.  c  o  m*/
    try {
        fileName = new StringBody(filename);
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(Example.class.getName()).log(Level.SEVERE, null, ex);
    }

    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("file", bin);
    reqEntity.addPart("filename", fileName);
    httppost.setEntity(reqEntity);

    HttpResponse response = null;
    try {
        response = httpclient.execute(httppost);
    } catch (IOException ex) {
        Logger.getLogger(Example.class.getName()).log(Level.SEVERE, null, ex);
    }
    HttpEntity resEntity = response.getEntity();

}

From source file:chat.parse.ChatParse.java

/**
 * @param args the command line arguments
 *//*from  www . j  ava2s  .  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 ww.ja v a  2s . c  o m
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.apache.httpclient.HttpPostExample.java

public static void main(String[] args) throws UnsupportedEncodingException {
    /* Create object of CloseableHttpClient */
    CloseableHttpClient httpClient = HttpClients.createDefault();

    /* Prepare POST request */
    HttpPost httpPost = new HttpPost("http://www.example.com/api/customer");
    /* Add headers to POST request */
    httpPost.addHeader("Authorization", "value");
    httpPost.addHeader("Content-Type", "application/json");

    /* Prepare StringEntity from JSON */
    StringEntity jsonData = new StringEntity("{\"id\":\"123\", \"name\":\"Vicky Thakor\"}", "UTF-8");
    /* Body of request */
    httpPost.setEntity(jsonData);// w  w  w.  ja v a 2  s .  c om

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

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

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

From source file:at.orz.arangodb.sandbox.PostChunkTest.java

/**
 * @param args//  w  ww .  ja va 2 s  . co m
 */
public static void main(String[] args) throws Exception {

    HttpClient client = new DefaultHttpClient();

    HttpPost post = new HttpPost(
            "http://arango-test-server:9999/_api/import?collection=test1&createCollection=true&type=documents");
    //post.setEntity(new StringEntity("{\"xx\": \"123\"}{\"xx\": \"456\"}"));
    InputStreamEntity entity = new InputStreamEntity(
            new ByteArrayInputStream("{\"xx\": \"123\"}{\"xx\": \"456\"}".getBytes()), 26);
    entity.setChunked(true);
    post.setEntity(entity);

    HttpResponse res = client.execute(post);

    System.out.println(res.getStatusLine());

    post.releaseConnection();
}

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);/*from   w w w  .  ja 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: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   w ww.j  a v  a  2  s .  c  om*/
    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: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  . j a v a 2  s .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();

    }

}