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:downloadwolkflow.getWorkFlowList.java

public static void main(String args[]) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String[] pageList = getPageList();
    System.out.println(pageList.length);
    for (int i = 1; i < pageList.length; i++) {
        System.out.println(pageList[i]);
        System.out.println("---------------------------------------------------------------------------");
        HttpGet httpget = new HttpGet(pageList[i]);
        try {/* w w w .ja  v a  2 s.  co m*/
            HttpResponse response = httpclient.execute(httpget);
            String page = EntityUtils.toString(response.getEntity());
            Document mainDoc = Jsoup.parse(page);
            Elements resultList = mainDoc.select("div.resource_list_item");
            for (int j = 0; j < resultList.size(); j++) {
                Element workflowResult = resultList.get(j);
                Element detailInfo = workflowResult.select("div.main_panel").first().select("p.title.inline")
                        .first().select("a").first();
                String detailUrl = "http://www.myexperiment.org" + detailInfo.attributes().get("href")
                        + ".html";
                System.out.println(detailUrl);
                downloadWorkFlow(detailUrl, httpclient);
                Thread.sleep(1000);
            }
        } catch (IOException ex) {
            Logger.getLogger(getWorkFlowList.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(getWorkFlowList.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    try {
        httpclient.close();
    } catch (IOException ex) {
        Logger.getLogger(getWorkFlowList.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:nl.raja.niruraji.pa.PlayGround.java

public static void main(String[] args) {

    try {//from ww  w  .j av a  2 s.c  o  m
        // create HTTP Client         
        HttpClient httpClient = HttpClientBuilder.create().build();
        String url = "http://buienradar.nl/Json/GetTwentyFourHourForecast?geolocationid=2751773";

        // Create new getRequest with below mentioned URL         
        HttpGet getRequest = new HttpGet(url);

        // Add additional header to getRequest which accepts application/xml data         
        //getRequest.addHeader("accept", "application/xml"); 

        // Execute your request and catch response         
        HttpResponse response = httpClient.execute(getRequest);

        // Check for HTTP response code: 200 = success         
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());

        }

        String result = EntityUtils.toString(response.getEntity());
        JSONObject myObject = new JSONObject(result);

        // Get-Capture Complete application/xml body response

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;

        System.out.println("============Output:============");

        // Simply iterate through XML response and show on console.

        while ((output = br.readLine()) != null) {

            System.out.println(output);

        }

    } catch (ClientProtocolException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

}

From source file:com.jkoolcloud.client.samples.query.QueryData1.java

public static void main(String[] args) {
    try {// ww w.  jav  a  2s . c o  m
        Properties props = new Properties();
        props.setProperty(JKCmdOptions.PROP_URI, JKQuery.JKOOL_QUERY_URL);
        JKCmdOptions options = new JKCmdOptions(QueryData1.class, args, props);
        if (options.usage != null) {
            System.out.println(options.usage);
            System.exit(-1);
        }
        options.print();
        JKQuery jkQuery = new JKQuery(options.token);
        HttpResponse response = jkQuery.get(options.query);
        System.out.println(EntityUtils.toString(response.getEntity()));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:downloadwolkflow.httpTest.java

public final static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//from www.  j a  va 2 s .  c o  m
        HttpGet httpget = new HttpGet(
                "http://www.myexperiment.org/workflows/16/download/Pathways_and_Gene_annotations_for_QTL_region-v7.t2flow?version=7");

        //System.out.println("Executing request " + httpget.getRequestLine());

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

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

        };
        String responseBody = httpclient.execute(httpget, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);
    } finally {
        httpclient.close();
    }
}

From source file:hackathon.Hackathon.java

/**
 * @param args the command line arguments
 *//*www  .ja va2  s  . c  o m*/
public static void main(String[] args) {
    // TODO code application logic here
    HttpClient httpclient = HttpClients.createDefault();

    try {
        URIBuilder builder = new URIBuilder(
                "https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize");

        URI uri = builder.build();
        HttpPost request = new HttpPost(uri);
        request.setHeader("Content-Type", "application/json");
        request.setHeader("Ocp-Apim-Subscription-Key", "3532e4ff429c4cce9baa783451db8b3b");

        // Request body
        String url = "https://s-media-cache-ak0.pinimg.com/564x/af/8b/47/af8b47d56ded6952fa8ebfdcf7e87f43.jpg";
        StringEntity reqEntity = new StringEntity(
                "{'url' : 'https://s-media-cache-ak0.pinimg.com/564x/af/8b/47/af8b47d56ded6952fa8ebfdcf7e87f43.jpg'}");
        request.setEntity(reqEntity);

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

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

From source file:com.javaquery.apache.httpclient.HttpDeleteExample.java

public static void main(String[] args) {
    /* Create object of CloseableHttpClient */
    CloseableHttpClient httpClient = HttpClients.createDefault();

    /* Prepare delete request */
    HttpDelete httpDelete = new HttpDelete("http://www.example.com/api/customer");
    /* Add headers to get request */
    httpDelete.addHeader("Authorization", "value");

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

        @Override//from   w ww. j  av  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(httpDelete, responseHandler);
        /* Print the response */
        System.out.println("Response: " + strResponse);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.javaquery.apache.httpclient.HttpGetExample.java

public static void main(String[] args) {
    /* Create object of CloseableHttpClient */
    CloseableHttpClient httpClient = HttpClients.createDefault();

    /* Prepare get request */
    HttpGet httpGet = new HttpGet("http://www.example.com/api/customer");
    /* Add headers to get request */
    httpGet.addHeader("Authorization", "value");
    httpGet.addHeader("Content-Type", "application/json");

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

        @Override/*from w  ww.  j av  a  2s .c  o m*/
        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(httpGet, responseHandler);
        /* Print the response */
        System.out.println("Response: " + strResponse);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.cloudhopper.httpclient.util.HttpsGetMain.java

static public void main(String[] args) throws Exception {
    ///*from ww  w  .j av  a 2s .c om*/
    // target urls
    //
    String strURL = "https://localhost:9443/";

    DefaultHttpClient client = new DefaultHttpClient();

    // setup this client to not verify SSL certificates
    HttpClientFactory.configureWithNoSslCertificateVerification(client);

    // add pre-emptive authentication
    HttpClientFactory.configureWithPreemptiveBasicAuth(client, "user0", "pass0");

    HttpGet get = new HttpGet(strURL);

    HttpResponse httpResponse = client.execute(get);

    HttpEntity responseEntity = httpResponse.getEntity();

    //
    // was the request OK?
    //
    if (httpResponse.getStatusLine().getStatusCode() != 200) {
        logger.error("Request failed with StatusCode=" + httpResponse.getStatusLine().getStatusCode());
    }

    // get an input stream
    String responseBody = EntityUtils.toString(responseEntity);

    logger.debug("----------------------------------------");
    logger.debug(responseBody);
    logger.debug("----------------------------------------");

    client.getConnectionManager().shutdown();
}

From source file:com.javaquery.apache.httpclient.HttpPutExample.java

public static void main(String[] args) {
    /* Create object of CloseableHttpClient */
    CloseableHttpClient httpClient = HttpClients.createDefault();

    /* Prepare put request */
    HttpPut httpPut = new HttpPut("http://www.example.com/api/customer");
    /* Add headers to get request */
    httpPut.addHeader("Authorization", "value");

    /* Prepare StringEntity from JSON */
    StringEntity jsonData = new StringEntity("{\"id\":\"123\", \"name\":\"Vicky Thakor\"}", "UTF-8");
    /* Body of request */
    httpPut.setEntity(jsonData);// w  ww.j  a va  2 s . c  o m

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

        @Override
        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(httpPut, responseHandler);
        /* Print the response */
        System.out.println("Response: " + strResponse);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:zz.pseas.ghost.login.weibo.WeibocnLogin.java

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

    // ?URL//ww w  .  j  av a 2s.  co m
    String Loginurl = "http://login.weibo.cn/login/";
    String firstpage = "http://weibo.cn/?vt=4"; // ??
    String loginnum = "test";
    String loginpwd = "test";

    CloseableHttpClient httpclient = HttpClients.createDefault(); // 
    HttpGet httpget = new HttpGet(Loginurl);

    try {
        CloseableHttpResponse response = httpclient.execute(httpget);

        String responhtml = null;
        try {
            responhtml = EntityUtils.toString(response.getEntity());
            // System.out.println(responhtml);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        // vk?,splithtml,??
        String vk = responhtml.split("<input type=\"hidden\" name=\"vk\" value=\"")[1].split("\" /><input")[0];
        System.out.println(vk);

        String pass = vk.split("_")[0];
        String finalpass = "password_" + pass;
        System.out.println(finalpass);
        response.close();

        List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
        pairs.add(new BasicNameValuePair("mobile", loginnum));
        pairs.add(new BasicNameValuePair(finalpass, loginpwd));
        pairs.add(new BasicNameValuePair("remember", "on"));
        pairs.add(new BasicNameValuePair("vk", vk));

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, Consts.UTF_8); // 
        HttpPost httppost = new HttpPost(Loginurl);
        httppost.setEntity(entity);
        // ???
        CloseableHttpResponse response2 = httpclient.execute(httppost);
        System.out.println(response2.getStatusLine().toString());
        httpclient.execute(httppost); // ?
        System.out.println("success");

        HttpGet getinfo = new HttpGet("http://m.weibo.cn/p/100803?vt=4");
        CloseableHttpResponse res;
        res = httpclient.execute(getinfo);
        System.out.println("??:");
        // ?html
        System.out.println(EntityUtils.toString(res.getEntity()));
        res.close();

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}