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:org.wso2.carbon.sample.pizzadelivery.client.PizzaDeliveryClient.java

public static void main(String[] args) {

    KeyStoreUtil.setTrustStoreParams();//from www .ja  va2 s  .c  o  m
    String url = args[0];
    String username = args[1];
    String password = args[2];

    HttpClient httpClient = new SystemDefaultHttpClient();

    try {
        HttpPost method = new HttpPost(url);

        if (httpClient != null) {
            String[] xmlElements = new String[] {
                    "<mypizza:PizzaDeliveryStream xmlns:mypizza=\"http://samples.wso2.org/\">\n"
                            + "        <mypizza:PizzaDelivery>\n"
                            + "              <mypizza:OrderNo>0023</mypizza:OrderNo>\n"
                            + "              <mypizza:PaymentType>Card</mypizza:PaymentType>\n"
                            + "              <mypizza:Address>29BX Finchwood Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaDelivery>\n" + "</mypizza:PizzaDeliveryStream>",
                    "<mypizza:PizzaDeliveryStream xmlns:mypizza=\"http://samples.wso2.org/\">\n"
                            + "        <mypizza:PizzaDelivery>\n"
                            + "              <mypizza:OrderNo>0024</mypizza:OrderNo>\n"
                            + "              <mypizza:PaymentType>Card</mypizza:PaymentType>\n"
                            + "              <mypizza:Address>2CYL Morris Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaDelivery>\n" + "</mypizza:PizzaDeliveryStream>",
                    "<mypizza:PizzaDeliveryStream xmlns:mypizza=\"http://samples.wso2.org/\">\n"
                            + "        <mypizza:PizzaDelivery>\n"
                            + "              <mypizza:OrderNo>0025</mypizza:OrderNo>\n"
                            + "              <mypizza:PaymentType>Cash</mypizza:PaymentType>\n"
                            + "              <mypizza:Address>22RE Robinwood Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaDelivery>\n" + "</mypizza:PizzaDeliveryStream>",
                    "<mypizza:PizzaDeliveryStream xmlns:mypizza=\"http://samples.wso2.org/\">\n"
                            + "        <mypizza:PizzaDelivery>\n"
                            + "              <mypizza:OrderNo>0026</mypizza:OrderNo>\n"
                            + "              <mypizza:PaymentType>Card</mypizza:PaymentType>\n"
                            + "              <mypizza:Address>29BX Finchwood Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaDelivery>\n" + "</mypizza:PizzaDeliveryStream>" };

            try {
                for (String xmlElement : xmlElements) {
                    StringEntity entity = new StringEntity(xmlElement);
                    method.setEntity(entity);
                    if (url.startsWith("https")) {
                        processAuthentication(method, username, password);
                    }
                    httpClient.execute(method).getEntity().getContent().close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            Thread.sleep(500); // We need to wait some time for the message to be sent

        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:httpclient.UploadAction.java

public static void main(String[] args) throws FileNotFoundException {
    File targetFile1 = new File("F:\\2.jpg");
    // File targetFile2 = new File("F:\\1.jpg");
    FileInputStream fis1 = new FileInputStream(targetFile1);
    // FileInputStream fis2 = new FileInputStream(targetFile2);
    // String targetURL =
    // "http://static.fangbiandian.com.cn/round_server/upload/uploadFile.do";
    String targetURL = "http://www.fangbiandian.com.cn/round_server/user/updateUserInfo.do";
    HttpPost filePost = new HttpPost(targetURL);
    try {/*from w w w  .ja  v a 2s .  c  o  m*/
        // ?????
        HttpClient client = new DefaultHttpClient();
        // FormBodyPart fbp1 = new FormBodyPart("file1", new
        // FileBody(targetFile1));
        // FormBodyPart fbp2 = new FormBodyPart("file2", new
        // FileBody(targetFile2));
        // FormBodyPart fbp3 = new FormBodyPart("file3", new
        // FileBody(targetFile3));
        // List<FormBodyPart> picList = new ArrayList<FormBodyPart>();
        // picList.add(fbp1);
        // picList.add(fbp2);
        // picList.add(fbp3);
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userId", "65478A5CD8D20C3807EE16CF22AF8A17");
        Map<String, Object> map = new HashMap<String, Object>();
        String jsonStr = JSON.toJSONString(paramMap);
        map.put("cid", 321);
        map.put("request", jsonStr);
        String jsonString = JSON.toJSONString(map);
        MultipartEntity multiEntity = new MultipartEntity();
        Charset charset = Charset.forName("UTF-8");
        multiEntity.addPart("request", new StringBody(jsonString, charset));
        multiEntity.addPart("photo", new InputStreamBody(fis1, "2.jpg"));
        // multiEntity.addPart("licenseUrl", new InputStreamBody(fis2,
        // "1.jpg"));
        filePost.setEntity(multiEntity);
        HttpResponse response = client.execute(filePost);
        int code = response.getStatusLine().getStatusCode();
        System.out.println(code);
        if (HttpStatus.SC_OK == code) {
            System.out.println("?");
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    // do something useful
                    BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
                    String str = null;
                    while ((str = reader.readLine()) != null) {
                        System.out.println(str);
                    }
                } finally {
                    instream.close();
                }
            }
        } else {
            System.out.println("");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        filePost.releaseConnection();
    }
}

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

public static void main(String[] args) {
    try {//from  w  w  w . ja  v a  2s  . 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();
    }
}

From source file:com.mycompany.mavenpost.HttpTest.java

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

    System.out.println("this is a test program");
    HttpPost httppost = new HttpPost("https://app.monsum.com/api/1.0/api.php");

    // Request parameters and other properties.
    String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
    byte[] encodedAuth = Base64.encodeBase64(auth.getBytes());
    String authHeader = "Basic " + new String(encodedAuth);
    //String authHeader = "Basic " +"YW5kcmVhcy5zZWZpY2hhQG1hcmtldHBsYWNlLWFuYWx5dGljcy5kZTo5MGRkYjg3NjExMWRiNjNmZDQ1YzUyMjdlNTNmZGIyYlhtMUJQQm03OHhDS1FUVm1OR1oxMHY5TVVyZkhWV3Vh";

    httppost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);

    httppost.setHeader(HttpHeaders.CONTENT_TYPE, "Content-Type: application/json");

    Map<String, Object> params = new LinkedHashMap<>();
    params.put("SERVICE", "customer.get");

    JSONObject json = new JSONObject();
    json.put("SERVICE", "customer.get");

    //Map<String, Object> params2 = new LinkedHashMap<>();

    //params2.put("CUSTOMER_NUMBER","5");
    JSONObject array = new JSONObject();
    array.put("CUSTOMER_NUMBER", "2");

    json.put("FILTER", array);

    StringEntity param = new StringEntity(json.toString());
    httppost.setEntity(param);//from w w w  .java2  s  .c o m

    HttpClient client = HttpClientBuilder.create().build();
    HttpResponse response = client.execute(httppost);

    int statusCode = response.getStatusLine().getStatusCode();
    System.out.println("The status code is  " + statusCode);

    //Execute and get the response.
    HttpEntity entity = response.getEntity();

    Header[] headers = response.getAllHeaders();
    for (Header header : headers) {
        System.out.println("Key : " + header.getName() + " ,Value : " + header.getValue());
    }
    if (entity != null) {
        String retSrc = EntityUtils.toString(entity); //Discouraged better open a stream and read the data as per Apache manual                     
        // parsing JSON
        //JSONObject result = new JSONObject(retSrc);
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JsonParser jp = new JsonParser();
        JsonElement je = jp.parse(retSrc);
        String prettyJsonString = gson.toJson(je);
        System.out.println(prettyJsonString);
    }
    //if (entity != null) {
    //    InputStream instream = entity.getContent();
    //    try {
    //  final BufferedReader reader = new BufferedReader(
    //                    new InputStreamReader(instream));
    //            String line = null;
    //            while ((line = reader.readLine()) != null) {
    //                System.out.println(line);
    //            }
    //            reader.close();
    //    } finally {
    //        instream.close();
    //    }
    //}
}

From source file:org.camunda.bpm.RestDeployment.java

public static void main(String[] args) throws IOException {
    if (args.length == 0) {
        System.err.println("No process files specified");
        System.exit(1);/*from   w  w  w  . java2 s .  c  o  m*/
    }

    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost("http://localhost:8080/engine-rest/deployment/create");

    StringBody deploymentName = new StringBody("myDeployment", ContentType.TEXT_PLAIN);
    StringBody enableDuplicateFiltering = new StringBody("true", ContentType.TEXT_PLAIN);
    StringBody deployChangedOnly = new StringBody("true", ContentType.TEXT_PLAIN);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create().addPart("deployment-name", deploymentName)
            .addPart("enable-duplicate-filtering", enableDuplicateFiltering)
            .addPart("deploy-changed-only", deployChangedOnly);

    for (String resource : args) {
        File resourceFile = new File(resource);
        FileBody fileBody = new FileBody(resourceFile);
        builder.addPart(resourceFile.getName(), fileBody);
    }

    HttpEntity httpEntity = builder.build();
    httpPost.setEntity(httpEntity);

    HttpResponse response = httpClient.execute(httpPost);

    logResponse(response);
}

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 {/*from   w ww .j a  v a 2s.com*/

        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:org.vuphone.vandyupon.test.EventPostTester.java

public static void main(String[] args) {
    HttpClient c = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://localhost:8080/vandyupon/events/");
    post.addHeader("Content-Type", "application/x-www-form-urlencoded");

    String params = "type=eventratingrequest&id=1&comments=true&numcom=10";
    post.setEntity(new ByteArrayEntity(params.toString().getBytes()));

    try {/*from ww  w .  ja  v  a  2s  .  com*/
        HttpResponse resp = c.execute(post);
        resp.getEntity().writeTo(System.out);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:org.vuphone.vandyupon.test.EventRatingPostTest.java

public static void main(String[] args) {
    HttpClient c = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://localhost:8080/vandyupon/events/");
    post.addHeader("Content-Type", "application/x-www-form-urlencoded");

    String params = "type=eventratingpost&event=1&user=chris&comment=awesome&value=1&resp=xml";
    post.setEntity(new ByteArrayEntity(params.toString().getBytes()));

    try {/*from www .  j a  va 2 s .c o m*/
        HttpResponse resp = c.execute(post);
        resp.getEntity().writeTo(System.out);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:org.vuphone.vandyupon.test.EventRequestTester.java

public static void main(String[] args) {
    HttpClient c = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://localhost:8080/vandyupon/events/");
    post.addHeader("Content-Type", "application/x-www-form-urlencoded");

    String params = "type=eventrequest&lat=36.1437&lon=-86.8046&dist=100&resp=xml&userid=chris";
    post.setEntity(new ByteArrayEntity(params.toString().getBytes()));

    try {/* w ww. j  a va2  s.  c o m*/
        HttpResponse resp = c.execute(post);
        resp.getEntity().writeTo(System.out);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:org.vuphone.vandyupon.test.EventMetaRequestTester.java

public static void main(String[] args) {
    HttpClient c = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://localhost:8080/vandyupon/events/");
    post.addHeader("Content-Type", "application/x-www-form-urlencoded");

    String params = "type=eventmetarequest&id=2&resp=xml";
    post.setEntity(new ByteArrayEntity(params.toString().getBytes()));

    try {/*from ww  w  . j a  v  a  2  s .c o  m*/
        HttpResponse resp = c.execute(post);
        resp.getEntity().writeTo(System.out);
    } catch (IOException e) {
        e.printStackTrace();
    }
}