Example usage for org.apache.http.util EntityUtils toString

List of usage examples for org.apache.http.util EntityUtils toString

Introduction

In this page you can find the example usage for org.apache.http.util EntityUtils toString.

Prototype

public static String toString(HttpEntity httpEntity) throws IOException, ParseException 

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  w w w.j  ava2  s.co  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: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);
    //        }// w w  w .  ja va  2 s  . com
    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:myexamples.QuickStart.java

public static void main(String[] args) throws Exception {
    Gson gson = new Gson();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {// w ww .j  a v  a  2  s .c o  m
        HttpGet httpGet = new HttpGet("http://localhost:9200/gb/tweet/9");
        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
            if (entity1 != null) {
                long len = entity1.getContentLength();
                if (len != -1 && len < 2048) {
                    System.out.println(EntityUtils.toString(entity1));
                } else {
                    System.out.println("entity length=" + len);
                }
            }
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }
        /*
                    HttpPost httpPost = new HttpPost("http://targethost/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: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);//  w ww  .  jav  a  2s  . 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:demo.example.ClientProxyAuthentication.java

public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", 8888),
            new UsernamePasswordCredentials("squid", "squid"));
    credsProvider.setCredentials(new AuthScope("httpbin.org", 80),
            new UsernamePasswordCredentials("user", "passwd"));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {/*w w w .  j a v a  2 s .c  o  m*/
        HttpHost target = new HttpHost("httpbin.org", 80, "http");
        HttpHost proxy = new HttpHost("localhost", 8888);

        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpGet httpget = new HttpGet("/basic-auth/user/passwd");
        httpget.setConfig(config);

        System.out.println("Executing request " + httpget.getRequestLine() + " to " + target + " via " + proxy);

        CloseableHttpResponse response = httpclient.execute(target, httpget);
        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.atlbike.etl.service.ClientFormLogin.java

/**
 * @param args//from w w  w.ja  v a2  s .  c  o  m
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    String authenticityToken = "";
    BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore)
            .setRedirectStrategy(new LaxRedirectStrategy()).build();
    try {
        HttpGet httpget = new HttpGet("https://atlbike.nationbuilder.com/login");
        CloseableHttpResponse response1 = httpclient.execute(httpget);
        try {
            HttpEntity entity = response1.getEntity();
            System.out.println("Content Length: " + entity.getContentLength());

            System.out.println("Login form get: " + response1.getStatusLine());
            // EntityUtils.consume(entity);
            String content = EntityUtils.toString(entity);
            Document doc = Jsoup.parse(content);
            Elements metaElements = doc.select("META");
            for (Element elem : metaElements) {
                System.out.println(elem);
                if (elem.hasAttr("name") && "csrf-token".equals(elem.attr("name"))) {
                    System.out.println("Value: " + elem.attr("content"));
                    authenticityToken = elem.attr("content");
                }
            }

            System.out.println("Initial set of cookies:");
            List<Cookie> cookies = cookieStore.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 {
            response1.close();
        }

        HttpUriRequest login = RequestBuilder.post()
                .setUri(new URI("https://atlbike.nationbuilder.com/forms/user_sessions"))
                .addParameter("email_address", "").addParameter("user_session[email]", "email@domain")
                .addParameter("user_session[password]", "magicCookie")
                .addParameter("user_session[remember_me]", "1").addParameter("commit", "Sign in with email")
                .addParameter("authenticity_token", authenticityToken).build();
        CloseableHttpResponse response2 = httpclient.execute(login);
        try {
            HttpEntity entity = response2.getEntity();
            // for (Header h : response2.getAllHeaders()) {
            // System.out.println(h);
            // }
            System.out.println("Content Length: " + entity.getContentLength());

            System.out.println("Login form get: " + response2.getStatusLine());
            EntityUtils.consume(entity);

            System.out.println("Post logon cookies:");
            List<Cookie> cookies = cookieStore.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 {
            response2.close();
        }

        httpget = new HttpGet(
                // HttpUriRequest file = RequestBuilder
                // .post()
                // .setUri(new URI(
                "https://atlbike.nationbuilder.com/admin/membership_types/14/download");
        // .build();
        // CloseableHttpResponse response3 = httpclient.execute(file);
        CloseableHttpResponse response3 = httpclient.execute(httpget);
        try {
            HttpEntity entity = response3.getEntity();
            System.out.println("Content Length: " + entity.getContentLength());

            System.out.println("File Get: " + response3.getStatusLine());
            saveEntity(entity);
            // EntityUtils.consume(entity);

            System.out.println("Post file get cookies:");
            List<Cookie> cookies = cookieStore.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 {
            response3.close();
        }

    } finally {
        httpclient.close();
    }
}

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

public static void main(String[] args) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//w ww .  j  a  v a  2 s.c  om
        httpclient.getParams().setParameter("socks.host", "mysockshost");
        httpclient.getParams().setParameter("socks.port", 1234);
        httpclient.getConnectionManager().getSchemeRegistry()
                .register(new Scheme("http", 80, new MySchemeSocketFactory()));

        HttpHost target = new HttpHost("www.apache.org", 80, "http");
        HttpGet req = new HttpGet("/");

        System.out.println("executing request to " + target + " via SOCKS proxy");
        HttpResponse rsp = httpclient.execute(target, req);
        HttpEntity entity = rsp.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(rsp.getStatusLine());
        Header[] headers = rsp.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            System.out.println(headers[i]);
        }
        System.out.println("----------------------------------------");

        if (entity != null) {
            System.out.println(EntityUtils.toString(entity));
        }

    } 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:ClientWithResponseHandlerPost.java

public final static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//www .  j av a2s .  co  m
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("id", "KYacxNZ6QQc"));
        formparams.add(new BasicNameValuePair("calid", "adamm"));
        formparams.add(new BasicNameValuePair("content-out", "text/xml"));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);

        //entity.setChunked(true);
        HttpPost httppost = new HttpPost("http://localhost:8080/export.wcap");
        httppost.setEntity(entity);

        System.out.println("executing request " + httppost.getURI());
        System.out.println("executing request " + httppost.getConfig());

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 600) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }

        };
        String responseBody = httpclient.execute(httppost, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);
        System.out.println("----------------------------------------");

    } finally {
        httpclient.close();
    }
}

From source file:com.cland.accessstats.util.QuickStart.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//from w  ww .  j  av  a  2 s  .  c om
        String origins = "-33.869952,18.537687";
        String destinations = "-33.96979309231926,18.53386491408955|-33.90630759128996,18.40310809285091|-33.97761,18.46555";
        String avoid = GMatrix.AVOID_HIGHWAYS + "|" + GMatrix.AVOID_TOLLS;
        String units = GMatrix.UNITS_DEFAULT;
        String language = "";
        boolean sensor = true;
        String url = GMatrix.getUrl(origins, destinations, GMatrix.JSON, GMatrix.MOD_DRIVING, avoid, units,
                language, sensor);
        System.out.println("Connection to... " + url);
        //GET EXAMPLE
        HttpGet httpGet = new HttpGet(url);
        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
            String result = EntityUtils.toString(entity1);
            // and ensure it is fully consumed
            EntityUtils.consume(entity1);

            //Process the result json data in the the into a collection DataEntry objects
            int num = 3; //we requested for 3 destinations
            List<DataEntry> dataentries = new ArrayList<DataEntry>();
            for (int i = 0; i < num; i++) {
                String distance = GMatrix.getDistanceText(result, 0, i);
                String duration = GMatrix.getDurationText(result, 0, i);
                DataEntry d = new DataEntry();
                d.setName("DESTINATION " + (i + 1));
                d.setDistance(distance);
                d.setTravelTime(duration);
                dataentries.add(d);

                //                   System.out.println(">>> DESTINATION " + i);
                //                   System.out.println(">>>Distance text: " + distance);
                //                  System.out.println(">>>Duration : " + duration);

            } //end for loop

            //Now we can return the collection as JSON at this ONLY has google data only
            //Lets see wat we have so far

            for (DataEntry e : dataentries) {
                System.out.println(">>> " + e.getName() + ": Distance=" + e.getDistance() + ", Duration="
                        + e.getTravelTime());
            }

        } finally {
            response1.close();
        }

        // POST EXAMPLE
        //            HttpPost httpPost = new HttpPost("http://targethost/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:com.ds.test.ClientFormLogin.java

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

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*from w ww .j  av  a  2 s .com*/
        HttpGet httpget = new HttpGet("http://www.iteye.com/login");

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

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

        System.out.println("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());
            }
        }

        /* HeaderIterator hi = response.headerIterator();
         while(hi.hasNext()){
            System.out.println(hi.next());
         }
                 
         EntityUtils.consume(entity);
         */

        String token = parseHtml(EntityUtils.toString(entity));

        httpget.releaseConnection();

        System.out.println("********************************************************");

        HttpPost httpost = new HttpPost("http://www.iteye.com/login");

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("name", ""));
        nvps.add(new BasicNameValuePair("password", ""));
        nvps.add(new BasicNameValuePair("authenticity_token", token));

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

        System.out.println("********************************************************");

        HttpGet httpget2 = new HttpGet("http://www.iteye.com/login");

        HttpResponse response2 = httpclient.execute(httpget2);
        HttpEntity entity2 = response2.getEntity();

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

        print(response2);

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