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:com.test.httpClient.QuickStart.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from   w w w  .  jav  a 2 s  .c  om*/
        HttpGet httpGet = new HttpGet("http://www.baidu.com");
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally clause.
        // Please note that if response content is not fully consumed the underlying
        // connection cannot be safely re-used and will be shut down and discarded
        // by the connection manager.
        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }

        HttpPost httpPost = new HttpPost("http://www.baidu.com");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("username", "vip"));
        nvps.add(new BasicNameValuePair("password", "secret"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        CloseableHttpResponse response2 = httpclient.execute(httpPost);

        try {
            System.out.println(response2.getStatusLine());
            HttpEntity entity2 = response2.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity2);
        } finally {
            response2.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.cloudhopper.sxmp.Post.java

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

    String message = "Test With @ Character";
    //String message = "Tell Twitter what you're doing!\nStd msg charges apply. Send 'stop' to quit.\nVisit twitter.com or email help@twitter.com for help.";

    StringBuilder string0 = new StringBuilder(200).append("<?xml version=\"1.0\"?>\n")
            .append("<operation type=\"submit\">\n")
            .append(" <account username=\"customer1\" password=\"password1\"/>\n")
            .append(" <submitRequest referenceId=\"MYREF102020022\">\n")
            .append("  <operatorId>75</operatorId>\n").append("  <deliveryReport>true</deliveryReport>\n")
            .append("  <sourceAddress type=\"network\">40404</sourceAddress>\n")
            .append("  <destinationAddress type=\"international\">+13135551234</destinationAddress>\n")
            .append("  <text encoding=\"ISO-8859-1\">" + HexUtil.toHexString(message.getBytes("ISO-8859-1"))
                    + "</text>\n")
            .append(" </submitRequest>\n").append("</operation>\n").append("");

    /**//from ww w.  j a  va 2  s.  c om
    //.append("<!DOCTYPE chapter PUBLIC \"-//OASIS//DTD DocBook XML//EN\" \"../dtds/docbookx.dtd\">")
    //.append("<!DOCTYPE chapter PUBLIC \"-//OASIS//DTD DocBook XML//EN\">")
    .append("<submitRequest sequenceId=\"1000\">\n")
    .append("   <!-- this is a comment -->\n")
    .append("   <account username=\"testaccount\" password=\"testpassword\"/>\n")
    .append("   <option />\n")
    .append("   <messageRequest referenceId=\"MYMESSREF\">\n")
    //.append("       <sourceAddress>+13135551212</sourceAddress>\n")
    .append("       <destinationAddress>+13135551200</destinationAddress>\n")
    .append("       <text><![CDATA[Hello World]]></text>\n")
    .append("   </messageRequest>\n")
    .append("</submitRequest>")
    .append("");
     */

    // Get target URL
    String strURL = "http://localhost:9080/api/sxmp/1.0";

    // Get file to be posted
    //String strXMLFilename = args[1];
    //File input = new File(strXMLFilename);

    HttpClient client = new DefaultHttpClient();

    long totalStart = System.currentTimeMillis();

    for (int i = 0; i < 1; i++) {
        long start = System.currentTimeMillis();

        // execute request
        try {
            HttpPost post = new HttpPost(strURL);

            StringEntity entity = new StringEntity(string0.toString(), "ISO-8859-1");
            entity.setContentType("text/xml; charset=\"ISO-8859-1\"");
            post.setEntity(entity);

            ResponseHandler<String> responseHandler = new BasicResponseHandler();

            String responseBody = client.execute(post, responseHandler);
            long stop = System.currentTimeMillis();

            logger.debug("----------------------------------------");
            logger.debug("Response took " + (stop - start) + " ms");
            logger.debug(responseBody);
            logger.debug("----------------------------------------");
        } finally {
            // do nothing
        }
    }

    long totalEnd = System.currentTimeMillis();

    logger.debug("Response took " + (totalEnd - totalStart) + " ms");

}

From source file:com.guilhermehott.http_post_file.ClientMultipartFormPost.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//from  ww w  . j  a  v  a  2s .c  om
        HttpPost httppost = new HttpPost("http://www.servidor2.danfeonline.com.br");

        FileBody bin = new FileBody(new File("C:/Users/Guilherme/Downloads/CAMMINARE - NFE EM XML/teste.xml"));

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

        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();
    }
}

From source file:demo.test.tutorial_learn.QuickStart.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*  ww w.  j a  va 2  s  .co m*/
        HttpGet httpGet = new HttpGet("http://httpbin.org/get");
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally clause.
        // Please note that if response content is not fully consumed the underlying
        // connection cannot be safely re-used and will be shut down and discarded
        // by the connection manager.
        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }

        HttpPost httpPost = new HttpPost("http://httpbin.org/post");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("username", "vip"));
        nvps.add(new BasicNameValuePair("password", "secret"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        CloseableHttpResponse response2 = httpclient.execute(httpPost);

        try {
            System.out.println(response2.getStatusLine());
            HttpEntity entity2 = response2.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity2);
        } finally {
            response2.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:org.bimserver.build.CreateGitHubRelease.java

public static void main(String[] args) {
    String username = args[0];/*from www.j a v a  2  s . c  o  m*/
    String password = args[1];
    String repo = args[2];
    String project = args[3];
    String tagname = args[4];
    String name = args[5];
    String body = args[6];
    String draft = args[7];
    String prerelease = args[8];
    String filesString = args[9];
    String[] filenames = filesString.split(";");

    GitHubClient gitHubClient = new GitHubClient("api.github.com");
    gitHubClient.setCredentials(username, password);

    Map<String, String> map = new HashMap<String, String>();
    map.put("tag_name", tagname);
    // map.put("target_commitish", "test");
    map.put("name", name);
    map.put("body", body);
    //      map.put("draft", draft);
    //      map.put("prerelease", prerelease);
    try {
        String string = "/repos/" + repo + "/" + project + "/releases";
        System.out.println(string);
        JsonObject gitHubResponse = gitHubClient.post(string, map, JsonObject.class);
        System.out.println(gitHubResponse);
        String id = gitHubResponse.get("id").getAsString();

        HttpHost httpHost = new HttpHost("uploads.github.com", 443, "https");

        BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
        basicCredentialsProvider.setCredentials(new AuthScope(httpHost),
                new UsernamePasswordCredentials(username, password));

        HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier();

        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        CloseableHttpClient client = HttpClients.custom()
                .setDefaultCredentialsProvider(basicCredentialsProvider)
                .setHostnameVerifier((X509HostnameVerifier) hostnameVerifier).setSSLSocketFactory(sslsf)
                .build();

        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(httpHost, basicAuth);

        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(basicCredentialsProvider);
        context.setAuthCache(authCache);

        for (String filename : filenames) {
            File file = new File(filename);
            String url = "https://uploads.github.com/repos/" + repo + "/" + project + "/releases/" + id
                    + "/assets?name=" + file.getName();
            HttpPost post = new HttpPost(url);
            post.setHeader("Accept", "application/vnd.github.manifold-preview");
            post.setHeader("Content-Type", "application/zip");
            post.setEntity(new InputStreamEntity(new FileInputStream(file), file.length()));
            HttpResponse execute = client.execute(httpHost, post, context);
            execute.getEntity().getContent().close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
}

From source file:com.cloverframework.core.QuickStart.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from w ww. j  a v a  2s  .  co m*/
        HttpGet httpGet = new HttpGet("http://www.sina.com.cn/");
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally clause.
        // Please note that if response content is not fully consumed the underlying
        // connection cannot be safely re-used and will be shut down and discarded
        // by the connection manager.
        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }

        HttpPost httpPost = new HttpPost("http://www.sina.com.cn/login");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("username", "vip"));
        nvps.add(new BasicNameValuePair("password", "secret"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        CloseableHttpResponse response2 = httpclient.execute(httpPost);

        try {
            System.out.println(response2.getStatusLine());
            HttpEntity entity2 = response2.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity2);
        } finally {
            response2.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:edu.harvard.hul.ois.drs.pdfaconvert.clients.FormFileUploaderClientApplication.java

/**
 * Run the program.// ww  w  .j  av  a2 s.c o m
 * 
 * @param args First argument is path to the file to analyze; second (optional) is path to server for overriding default value.
 */
public static void main(String[] args) {
    // takes file path from first program's argument
    if (args.length < 1) {
        logger.error("****** Path to input file must be first argument to program! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    String filePath = args[0];
    File uploadFile = new File(filePath);
    if (!uploadFile.exists()) {
        logger.error("****** File does not exist at expected locations! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    if (args.length > 1) {
        serverUrl = args[1];
    }

    logger.info("File to upload: " + filePath);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(serverUrl);
        FileBody bin = new FileBody(uploadFile);
        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart(FORM_FIELD_DATAFILE, bin).build();
        httppost.setEntity(reqEntity);

        logger.info("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            logger.info("HTTP Response Status Line: " + response.getStatusLine());
            // Expecting a 200 Status Code
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                String reason = response.getStatusLine().getReasonPhrase();
                logger.warn("Unexpected HTTP response status code:[" + response.getStatusLine().getStatusCode()
                        + "] -- Reason (if available): " + reason);
            } else {
                HttpEntity resEntity = response.getEntity();
                InputStream is = resEntity.getContent();
                BufferedReader in = new BufferedReader(new InputStreamReader(is));

                String output;
                StringBuilder sb = new StringBuilder("Response data received:");
                while ((output = in.readLine()) != null) {
                    sb.append(System.getProperty("line.separator"));
                    sb.append(output);
                }
                logger.info(sb.toString());
                in.close();
                EntityUtils.consume(resEntity);
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        logger.error("Caught exception: " + e.getMessage(), e);
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            logger.warn("Exception closing HTTP client: " + e.getMessage(), e);
        }
        logger.info("DONE");
    }
}

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

public static void main(String[] args) throws Exception {
    if (args.length != 4 && args.length != 5) {
        System.err.println(/*from   w w  w .  j  a  v  a2s.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);

        for (File queryFile : queryFiles) {
            String query = new BufferedReader(new FileReader(queryFile)).readLine();
            httpPost.setEntity(new StringEntity("{\"pql\":\"" + 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:org.openeclass.EclassMobile.java

public static void main(String[] args) {

    try {//from ww  w.  jav a  2  s. c o m
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("https://myeclass/modules/mobile/mlogin.php");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("uname", mUsername));
        nvps.add(new BasicNameValuePair("pass", mPassword));
        httppost.setEntity(new UrlEncodedFormEntity(nvps));

        System.out.println("twra tha kanei add");
        System.out.println("prin to response");

        HttpResponse response = httpclient.execute(httppost);
        StatusLine status = response.getStatusLine();

        if (status.getStatusCode() != 200)
            System.out.println("Invalid response from server: " + status.toString());

        System.out.println("meta to response");

        Header[] head = response.getAllHeaders();

        for (int i = 0; i < head.length; i++)
            System.out.println("to head exei " + head[i]);

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

        HttpEntity entity = response.getEntity();
        InputStream ips = entity.getContent();
        BufferedReader buf = new BufferedReader(new InputStreamReader(ips, "UTF-8"), 1024);

        StringBuilder sb = new StringBuilder();
        String s = "";

        while ((s = buf.readLine()) != null) {
            sb.append(s);
        }
        System.out.println("to sb einai " + sb.toString());

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:httpclient.client.ClientFormLogin.java

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

    // prepare parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setUserAgent(params, Constants.BROWSER_TYPE);
    HttpProtocolParams.setUseExpectContinue(params, true);
    DefaultHttpClient httpclient = new DefaultHttpClient(params);

    String loginURL = "http://10.1.1.251/login.asp";
    HttpGet httpget = new HttpGet(loginURL);
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        entity.consumeContent();/*from   www  . ja  va 2 s .c om*/
    }
    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("- " + cookies.get(i).toString());
        }
    }

    HttpPost httpost = new HttpPost(loginURL);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("name", "fangdj"));
    nvps.add(new BasicNameValuePair("passwd", "1111"));

    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    response = httpclient.execute(httpost);
    entity = response.getEntity();
    for (Header h : response.getAllHeaders()) {
        System.out.println(h);
    }
    System.out.println("Login form get: " + response.getStatusLine());
    if (entity != null) {
        entity.consumeContent();
    }

    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("- " + cookies.get(i).toString());
        }
    }

    String mainURL = "http://10.1.1.251/ONWork/Record_save.asp";

    HttpPost mainHttPost = new HttpPost(mainURL);
    List<NameValuePair> mainNvps = new ArrayList<NameValuePair>();
    mainNvps.add(new BasicNameValuePair("EMP_NO", "13028"));
    mainNvps.add(new BasicNameValuePair("pwd", "1111"));
    mainNvps.add(new BasicNameValuePair("cmd2", "Apply"));

    httpost.setEntity(new UrlEncodedFormEntity(mainNvps, HTTP.UTF_8));

    response = httpclient.execute(mainHttPost);
    System.out.println(Tools.InputStreamToString(response.getEntity().getContent()));
    // When HttpClient instance is no longer needed, 
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
}