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.gemini.httpclienttest.HttpClientTestMain.java

public static void main(String[] args) {
    //authenticate with the server
    URL url;//  w  w  w .  j ava 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:at.orz.arangodb.sandbox.PostChunkTest.java

/**
 * @param args//from  w  w w.j  a  va2  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:org.wso2.carbon.sample.http.Http.java

public static void main(String args[]) {
    log.info("Starting WSO2 Http Client");
    HttpUtil.setTrustStoreParams();/*from w  w  w .  j  a  va2 s  . c om*/
    String url = args[0];
    String username = args[1];
    String password = args[2];
    String sampleNumber = args[3];
    String filePath = args[4];
    HttpClient httpClient = new SystemDefaultHttpClient();
    try {
        HttpPost method = new HttpPost(url);
        filePath = HttpUtil.getMessageFilePath(sampleNumber, filePath, url);
        readMsg(filePath);
        for (String message : messagesList) {
            StringEntity entity = new StringEntity(message);
            log.info("Sending message:");
            log.info(message + "\n");
            method.setEntity(entity);
            if (url.startsWith("https")) {
                processAuthentication(method, username, password);
            }
            httpClient.execute(method).getEntity().getContent().close();
        }
        Thread.sleep(500); // Waiting time for the message to be sent
    } catch (Throwable t) {
        log.error("Error when sending the messages", t);
    }
}

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

/**
 * Run the program./*from  www.  j a v 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 + "false");
        FileBody bin = new FileBody(uploadFile);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addPart(FITS_FORM_FIELD_DATAFILE, bin);
        HttpEntity reqEntity = builder.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();
                while ((output = in.readLine()) != null) {
                    sb.append(output);
                    sb.append(System.getProperty("line.separator"));
                }
                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.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);

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

        @Override/*from  www .j a  v  a  2  s . com*/
        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:httpclient.entity.mime.ClientMultipartFormPost.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. co  m*/
    }
    HttpClient httpclient = new DefaultHttpClient();

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

    FileBody bin = new FileBody(new File(args[0]));
    StringBody comment = new StringBody("A binary file of some kind");

    MultipartEntity reqEntity = new MultipartEntity();
    //        reqEntity.addPart("bin", bin);
    //        reqEntity.addPart("comment", comment);
    //        
    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();
    }
}

From source file:com.hilatest.httpclient.apacheexample.ClientFormLogin.java

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

    DefaultHttpClient httpclient = new DefaultHttpClient();

    HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");

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

    System.out.println("Login form get: " + response.getStatusLine());
    if (entity != null) {
        entity.consumeContent();//from ww  w . j  a v  a  2s  .c  o  m
    }
    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("https://portal.sun.com/amserver/UI/Login?" + "org=self_registered_users&"
            + "goto=/portal/dt&" + "gotoOnFail=/portal/dt?error=true");

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("IDToken1", "username"));
    nvps.add(new BasicNameValuePair("IDToken2", "password"));

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

    response = httpclient.execute(httpost);
    entity = response.getEntity();

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

    // 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.dlmu.heipacker.crawler.examples.entity.mime.ClientMultipartFormPost.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  av  a2 s .com*/
    }
    HttpClient httpclient = new DefaultHttpClient();
    try {
        HttpPost httppost = new HttpPost(
                "http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample");

        FileBody bin = new FileBody(new File(args[0]));
        StringBody comment = new StringBody("A binary file of some kind");

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("bin", bin);
        reqEntity.addPart("comment", comment);

        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());
        }
        EntityUtils.consume(resEntity);
    } finally {
        try {
            httpclient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
        }
    }
}

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

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

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {// ww  w.j  a  va 2s .  c o m
        HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");

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

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

        HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?"
                + "org=self_registered_users&" + "goto=/portal/dt&" + "gotoOnFail=/portal/dt?error=true");

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("IDToken1", "username"));
        nvps.add(new BasicNameValuePair("IDToken2", "password"));

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

        response = httpclient.execute(httpost);
        entity = response.getEntity();

        System.out.println("Login form get: " + response.getStatusLine());
        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("- " + 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:demo.example.ClientMultipartFormPost.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 v  a 2 s . co m
    }
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(
                "http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample");

        FileBody bin = new FileBody(new File(args[0]));
        StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment)
                .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();
    }
}