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

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

Introduction

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

Prototype

public void setEntity(final HttpEntity entity) 

Source Link

Usage

From source file:demo.example.ClientChunkEncodedPost.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println("File path not given");
        System.exit(1);//from  www  .j  a  va2  s  . c o m
    }
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost("http://httpbin.org/post");

        File file = new File(args[0]);

        InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1,
                ContentType.APPLICATION_OCTET_STREAM);
        reqEntity.setChunked(true);
        // It may be more appropriate to use FileEntity class in this particular
        // instance but we are using a more generic InputStreamEntity to demonstrate
        // the capability to stream out data from any arbitrary source
        //
        // FileEntity entity = new FileEntity(file, "binary/octet-stream");

        httppost.setEntity(reqEntity);

        System.out.println("Executing request: " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

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

public static void main(String[] args) {
    try {//from   w w w. ja  va  2  s  . co 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.hilatest.httpclient.apacheexample.ClientChunkEncodedPost.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println("File path not given");
        System.exit(1);/*from   w w  w  .j a va  2 s.  c  o  m*/
    }
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample");

    File file = new File(args[0]);

    InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
    reqEntity.setContentType("binary/octet-stream");
    reqEntity.setChunked(true);
    // It may be more appropriate to use FileEntity class in this particular 
    // instance but we are using a more generic InputStreamEntity to demonstrate
    // the capability to stream out data from any arbitrary source
    // 
    // FileEntity entity = new FileEntity(file, "binary/octet-stream"); 

    httppost.setEntity(reqEntity);

    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    if (resEntity != null) {
        System.out.println("Response content length: " + resEntity.getContentLength());
        System.out.println("Chunked?: " + resEntity.isChunked());
    }
    if (resEntity != null) {
        resEntity.consumeContent();
    }

    // When HttpClient instance is no longer needed, 
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
}

From source file:httpclientdemo.ClientChunkEncodedPost.java

public static void main(String[] args) throws Exception {
    //        if (args.length != 1)  {
    //            System.out.println("File path not given");
    //            System.exit(1);
    //        }// www  .  j a  va 2s  .  c om
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost("http://httpbin.org/post");

        File file = new File("/Users/jack/Downloads/listdata (1).xlsx");

        InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1,
                ContentType.APPLICATION_OCTET_STREAM);
        reqEntity.setChunked(true);
        // It may be more appropriate to use FileEntity class in this particular
        // instance but we are using a more generic InputStreamEntity to demonstrate
        // the capability to stream out data from any arbitrary source
        //
        // FileEntity entity = new FileEntity(file, "binary/octet-stream");

        httppost.setEntity(reqEntity);

        System.out.println("Executing request: " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.dlmu.heipacker.crawler.client.ClientChunkEncodedPost.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println("File path not given");
        System.exit(1);//ww w . jav  a2  s. co m
    }
    HttpClient httpclient = new DefaultHttpClient();
    try {
        HttpPost httppost = new HttpPost(
                "http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample");

        File file = new File(args[0]);

        InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
        reqEntity.setContentType("binary/octet-stream");
        reqEntity.setChunked(true);
        // It may be more appropriate to use FileEntity class in this particular
        // instance but we are using a more generic InputStreamEntity to demonstrate
        // the capability to stream out data from any arbitrary source
        //
        // FileEntity entity = new FileEntity(file, "binary/octet-stream");

        httppost.setEntity(reqEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            System.out.println("Response content length: " + resEntity.getContentLength());
            System.out.println("Chunked?: " + resEntity.isChunked());
        }
        EntityUtils.consume(resEntity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.springside.examples.schedule.TransferOaDataToGx.java

public static void main(String[] args) {
    //      /*from  w w  w .j  a  v a  2s  .c  o m*/
    //      // ?
    //      HttpPost httpPost = new HttpPost("http://gxoa.cc/login!login.do?userName=&userPassword=gxuser&loginState=1");
    //      
    //      // ?connection poolclient
    //      RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20 * 1000)
    //            .setConnectTimeout(20 * 1000).build();
    //
    //      CloseableHttpClient  httpClient = HttpClientBuilder.create().setMaxConnTotal(20).setMaxConnPerRoute(20)
    //            .setDefaultRequestConfig(requestConfig).build();
    //      try {
    //         CloseableHttpResponse  closeableHttpResponse = httpClient.execute(httpPost);
    //         System.out.println(IOUtils.toString(closeableHttpResponse.getEntity().getContent(), "UTF-8"));
    //         HttpGet httpGet = new HttpGet("http://gxoa.cc/attachmentDownload.do?filePath=2010-07/2010-07-28-4bdd9279-c09e-4b68-80fc-c9d049c6bdfc-GXTC-1005124--??20091062.rar");
    //         CloseableHttpResponse closeableHttpResponseFile = httpClient.execute(httpGet);
    //         //FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\"));
    //         System.out.println(IOUtils.toString(closeableHttpResponseFile.getEntity().getContent(), "UTF-8"));
    //
    //         
    //      } catch (ClientProtocolException e) {
    //         // TODO Auto-generated catch block
    //         e.printStackTrace();
    //      } catch (IOException e) {
    //         // TODO Auto-generated catch block
    //         e.printStackTrace();
    //      }

    //      

    HttpPost httpPost = new HttpPost("http://219.239.33.123:9090/quickstart/api/getFileFromFTP");

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();

    nvps.add(new BasicNameValuePair("filePath",
            "2015-04/2015-04-28-718f376f-b725-4e18-87e2-43e30124b2b5-GXTC-1506112-&-.rar"));

    String salt = "GXCX_OA_SALT";
    long currentTime = ((new Date().getTime() * 4 + 2) * 5 - 1) * 8 + 3;// by yucy
    String key = salt + currentTime;
    nvps.add(new BasicNameValuePair("key", Base64.encodeBase64String(key.getBytes())));

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    // ?connection poolclient
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20 * 1000)
            .setConnectTimeout(20 * 1000).build();
    CloseableHttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(20).setMaxConnPerRoute(20)
            .setDefaultRequestConfig(requestConfig).build();
    try {
        CloseableHttpResponse closeableHttpResponseFile = httpClient.execute(httpPost);

        FileUtils.writeByteArrayToFile(new File("D:/upload/templateBulletin.rar"),
                IOUtils.toByteArray(closeableHttpResponseFile.getEntity().getContent()));
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //TODO  ?
    //FileUtils.writeByteArrayToFile( file, FileUtils.readFileToByteArray( new File("D:/upload/templateBulletin.zip") ) );

}

From source file:com.linkedin.pinotdruidbenchmark.DruidResponseTime.java

public static void main(String[] args) throws Exception {
    if (args.length != 4 && args.length != 5) {
        System.err.println(//from   ww w .j  a  v  a 2  s .c om
                "4 or 5 arguments required: QUERY_DIR, RESOURCE_URL, WARM_UP_ROUNDS, TEST_ROUNDS, RESULT_DIR (optional).");
        return;
    }

    File queryDir = new File(args[0]);
    String resourceUrl = args[1];
    int warmUpRounds = Integer.parseInt(args[2]);
    int testRounds = Integer.parseInt(args[3]);
    File resultDir;
    if (args.length == 4) {
        resultDir = null;
    } else {
        resultDir = new File(args[4]);
        if (!resultDir.exists()) {
            if (!resultDir.mkdirs()) {
                throw new RuntimeException("Failed to create result directory: " + resultDir);
            }
        }
    }

    File[] queryFiles = queryDir.listFiles();
    assert queryFiles != null;
    Arrays.sort(queryFiles);

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpPost httpPost = new HttpPost(resourceUrl);
        httpPost.addHeader("content-type", "application/json");

        for (File queryFile : queryFiles) {
            StringBuilder stringBuilder = new StringBuilder();
            try (BufferedReader bufferedReader = new BufferedReader(new FileReader(queryFile))) {
                int length;
                while ((length = bufferedReader.read(CHAR_BUFFER)) > 0) {
                    stringBuilder.append(new String(CHAR_BUFFER, 0, length));
                }
            }
            String query = stringBuilder.toString();
            httpPost.setEntity(new StringEntity(query));

            System.out.println(
                    "--------------------------------------------------------------------------------");
            System.out.println("Running query: " + query);
            System.out.println(
                    "--------------------------------------------------------------------------------");

            // Warm-up Rounds
            System.out.println("Run " + warmUpRounds + " times to warm up...");
            for (int i = 0; i < warmUpRounds; i++) {
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                httpResponse.close();
                System.out.print('*');
            }
            System.out.println();

            // Test Rounds
            System.out.println("Run " + testRounds + " times to get response time statistics...");
            long[] responseTimes = new long[testRounds];
            long totalResponseTime = 0L;
            for (int i = 0; i < testRounds; i++) {
                long startTime = System.currentTimeMillis();
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                httpResponse.close();
                long responseTime = System.currentTimeMillis() - startTime;
                responseTimes[i] = responseTime;
                totalResponseTime += responseTime;
                System.out.print(responseTime + "ms ");
            }
            System.out.println();

            // Store result.
            if (resultDir != null) {
                File resultFile = new File(resultDir, queryFile.getName() + ".result");
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                try (BufferedInputStream bufferedInputStream = new BufferedInputStream(
                        httpResponse.getEntity().getContent());
                        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(resultFile))) {
                    int length;
                    while ((length = bufferedInputStream.read(BYTE_BUFFER)) > 0) {
                        bufferedWriter.write(new String(BYTE_BUFFER, 0, length));
                    }
                }
                httpResponse.close();
            }

            // Process response times.
            double averageResponseTime = (double) totalResponseTime / testRounds;
            double temp = 0;
            for (long responseTime : responseTimes) {
                temp += (responseTime - averageResponseTime) * (responseTime - averageResponseTime);
            }
            double standardDeviation = Math.sqrt(temp / testRounds);
            System.out.println("Average response time: " + averageResponseTime + "ms");
            System.out.println("Standard deviation: " + standardDeviation);
        }
    }
}

From source file:pt.ua.tm.neji.web.test.TestREST.java

public static void main(String[] args) throws IOException, KeyStoreException, NoSuchAlgorithmException,
        CertificateException, KeyManagementException, UnrecoverableKeyException {

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null, null);//from  w  w w  .  j a v a 2 s.  com

    MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", sf, 8010));

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

    String url = "https://localhost:8010/annotate/default/export?tool=becas-webapp&email=bioinformatics@ua.pt";

    // POST
    CloseableHttpClient client = new DefaultHttpClient(ccm, params);

    HttpPost post = new HttpPost(url);
    //post.setHeader("Content-Type", "application/json");

    List<NameValuePair> keyValuesPairs = new ArrayList();
    //keyValuesPairs.add(new BasicNameValuePair("format", "neji"));
    keyValuesPairs.add(new BasicNameValuePair("fromFile", "false"));
    //keyValuesPairs.add(new BasicNameValuePair("groups", "{\"DISO\":true,\"ANAT\":true}"));
    //keyValuesPairs.add(new BasicNameValuePair("groups", "{}"));
    //keyValuesPairs.add(new BasicNameValuePair("groups", "{\"DISO\":true}"));
    //keyValuesPairs.add(new BasicNameValuePair("groups", "{\"ANAT\":true}"));
    keyValuesPairs.add(new BasicNameValuePair("text", text));
    keyValuesPairs.add(new BasicNameValuePair("crlf", "false"));
    post.setEntity(new UrlEncodedFormEntity(keyValuesPairs));

    HttpResponse response = client.execute(post);

    String result = IOUtils.toString(response.getEntity().getContent());

    System.out.println(result);
}

From source file:com.da.img.ClientFormLogin.java

public static void main(String[] args) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();

    try {/*from   ww  w  .  j  a v a 2s.  co m*/
        HttpGet httpget = new HttpGet("http://www.soraven.info/index.php");

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        //System.out.println( EntityUtils.toString(entity));
        System.out.println("Login form get: " + response.getStatusLine());
        EntityUtils.consume(entity);

        System.out.println("Initial set of cookies:");
        List<Cookie> cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("-1 " + cookies.get(i).toString());
            }
        }

        HttpPost httpost = new HttpPost("http://www.soraven.info/common/include/login.php");
        Header header1 = new BasicHeader("Accept",
                "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,application/msword, */*");
        Header header2 = new BasicHeader("Referer", "http://www.soraven.info/index.php");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("p_userid", "bimohani"));
        nvps.add(new BasicNameValuePair("p_passwd", "cw8904"));
        nvps.add(new BasicNameValuePair("x", "12"));
        nvps.add(new BasicNameValuePair("y", "20"));
        httpost.setHeader(header1);
        httpost.setHeader(header2);
        httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

        //Thread.sleep(2000);
        response = httpclient.execute(httpost);
        entity = response.getEntity();

        System.out.println("Login form get: " + response.getStatusLine());

        System.out.println(EntityUtils.toString(entity));
        EntityUtils.consume(entity);

        System.out.println("Post logon cookies:");
        cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("-2 " + cookies.get(i).toString());
            }
        }

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.lexmark.saperion.util.ClientMultipartFormPost.java

public static void main(String[] args) throws Exception {
    String userName = "amolugu";
    String password = "ecm";
    String authString = userName + ":" + password;
    byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
    String authStringEnc = new String(authEncBytes);
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*  ww  w .j  a v a  2 s .com*/
        HttpPost httpPost = new HttpPost("https://ecm-service.psft.co/ecms/documents");

        //http
        httpPost.addHeader("Authorization", "Basic " + authStringEnc);
        httpPost.addHeader("Accept", "application/json");
        httpPost.addHeader("saTenant", "india");
        httpPost.addHeader("saLicense", "1");
        httpPost.addHeader("Content-Type", "application/octet-stream");

        FileBody bin = new FileBody(new File("C:\\Users\\Aditya.Molugu\\workspace\\RestClient\\Binaries.txt"));
        StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment)
                .build();

        //HttpBo
        httpPost.setEntity(reqEntity);

        System.out.println("executing request " + httpPost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpPost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
            }
            EntityUtils.consume(resEntity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}