Example usage for org.apache.http.client HttpClient execute

List of usage examples for org.apache.http.client HttpClient execute

Introduction

In this page you can find the example usage for org.apache.http.client HttpClient execute.

Prototype

HttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException;

Source Link

Document

Executes HTTP request using the default context.

Usage

From source file:com.mtea.macrotea_httpclient_study.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.ja v  a 2 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);
        // ?
        // 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 {
        //??httpclient???
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:postenergy.TestHttpClient.java

public static void main(String[] args) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");

    try {//  w w w.  j a v a 2 s.  co m

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("Email", "youremail"));
        nameValuePairs.add(new BasicNameValuePair("Passwd", "yourpassword"));
        nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
        nameValuePairs.add(new BasicNameValuePair("source", "Google-cURL-Example"));
        nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        String line = "";
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
            if (line.startsWith("Auth=")) {
                String key = line.substring(5);
                // do something with the key
            }

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

From source file:niclients.main.getni.java

/**
 * Main of the GET NI.// w ww . ja v  a 2  s  .  co  m
 */
@SuppressWarnings("unchecked")
public static void main(String[] args) throws UnsupportedEncodingException {
    HttpClient client = new DefaultHttpClient();
    boolean done;
    String dst = null;
    JSONArray loc_array = new JSONArray();
    String c_type;
    HttpResponse response;
    int resp_code = 0;

    if (commandparser(args)) {

        dst = fqdn;
        done = false;

        try {
            while (!done) {
                if (createget(dst, niname)) {

                    response = client.execute(post);
                    resp_code = response.getStatusLine().getStatusCode();

                    if (200 == resp_code) {
                        // Get content type
                        c_type = response.getEntity().getContentType().getValue();

                        if ("application/json".equalsIgnoreCase(c_type)) {
                            // Response is location list
                            InputStream content = response.getEntity().getContent();
                            String resp = convertStreamToString(content);

                            // String to JSONArray
                            Object obj = JSONValue.parse(resp);
                            JSONArray array = (JSONArray) obj;

                            // add new locations to loc_array   
                            for (int i = 0; i < array.size(); i++) {
                                loc_array.add(array.get(i));
                            }
                            // Get next location from the loc_array and remove it from the loc_array
                            if (!loc_array.isEmpty()) {

                                // Check if new dst is type ni://
                                String tmp_dst = loc_array.get(0).toString();
                                tmp_dst = niUtils.mapNiToWKU(loc_array.get(0).toString());

                                if (tmp_dst == null) {
                                    //Check id new dst is type nihttp://
                                    tmp_dst = niUtils.mapNiHttpToWKU(loc_array.get(0).toString());
                                    if (tmp_dst != null)
                                        // is nihttp://
                                        dst = tmp_dst;
                                    else
                                        // is http://
                                        dst = loc_array.get(0).toString();
                                } else {
                                    // is ni://
                                    dst = tmp_dst;
                                }
                                loc_array.remove(0);
                            }
                        } else if ("application/octet-stream".equalsIgnoreCase(c_type)) {
                            // Response is content
                            InputStream content = response.getEntity().getContent();
                            if (output_filename == null)
                                writeCacheCopyToStdOut(content);
                            else {
                                writeCacheCopy(content, output_filename);
                                System.err.println("Content was stored to '" + output_filename + "'");
                            }
                            // so we can end the while
                            done = true;
                        } else {
                            // Response content type is not something we expected
                            System.err.println("Unsupported Content type = " + c_type);
                        }
                    } else {
                        // Response codetype is not success (we expected that)
                        System.err.println("RESP_CODE: " + Integer.toString(resp_code));
                    }
                } else {
                    System.err.println("Command parse failed!");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:uk.co.techblue.docusign.client.DocuSignClient.java

public static void main(String[] args) throws ClientProtocolException, IOException {
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
    int maxPerRoute = 50;
    cm.setDefaultMaxPerRoute(maxPerRoute);
    cm.setMaxTotal(maxPerRoute);/*w  ww  .java2 s.com*/

    HttpClient client = new DefaultHttpClient(cm);
    HttpParams params = client.getParams();
    // Allowable time between packets
    HttpConnectionParams.setSoTimeout(params, 6000);
    // Allowable time to get a connection
    HttpConnectionParams.setConnectionTimeout(params, 6000);

    HttpGet request = new HttpGet(
            "https://demo.docusign.net/restapi/v2/accounts/672084/envelopes/e266ddb9-b293-4013-98fd-c121b7832d4a/audit_events");
    request.setHeader("Authorization", "bearer D/rZd4fBhOpg2r0VTipQC105ARE=");
    HttpResponse response = client.execute(request);

    System.out.println(response);
}

From source file:net.modelbased.proasense.storage.registry.StorageRegistrySensorDataTestClient.java

public static void main(String[] args) {
    // Get client properties from properties file
    //        StorageRegistrySensorDataTestClient client = new StorageRegistrySensorDataTestClient();
    //        client.loadClientProperties();

    // Hardcoded client properties (simple test client)
    String STORAGE_REGISTRY_SERVICE_URL = "http://192.168.84.34:8080/storage-registry";

    // Default HTTP client and common properties for requests
    HttpClient client = new DefaultHttpClient();
    StringBuilder requestUrl = null;
    List<NameValuePair> params = null;
    String queryString = null;//  w w w  .  ja  va2s. c  om

    // Default HTTP response and common properties for responses
    HttpResponse response = null;
    ResponseHandler<String> handler = null;
    int status = 0;
    String body = null;

    // Query for sensor list
    requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL);
    requestUrl.append("/query/sensor/list");

    try {
        HttpGet query21 = new HttpGet(requestUrl.toString());
        query21.setHeader("Content-type", "application/json");
        response = client.execute(query21);

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

        // Get body
        handler = new BasicResponseHandler();
        body = handler.handleResponse(response);

        System.out.println("SENSOR LIST: " + body);
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Query for sensor properties
    requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL);
    requestUrl.append("/query/sensor/properties");

    params = new LinkedList<NameValuePair>();
    params.add(new BasicNameValuePair("sensorId", "visualInspection"));

    queryString = URLEncodedUtils.format(params, "utf-8");
    requestUrl.append("?");
    requestUrl.append(queryString);

    try {
        HttpGet query22 = new HttpGet(requestUrl.toString());
        query22.setHeader("Content-type", "application/json");
        response = client.execute(query22);

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

        // Get body
        handler = new BasicResponseHandler();
        body = handler.handleResponse(response);

        System.out.println("SENSOR PROPERTIES: " + body);
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

From source file:httpclient.client.ClientEvictExpiredConnections.java

public static void main(String[] args) throws Exception {
    // Create and initialize HTTP parameters
    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 100);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

    // Create and initialize scheme registry 
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    HttpClient httpclient = new DefaultHttpClient(cm, params);

    // create an array of URIs to perform GETs on
    String[] urisToGet = { "http://jakarta.apache.org/", "http://jakarta.apache.org/commons/",
            "http://jakarta.apache.org/commons/httpclient/",
            "http://svn.apache.org/viewvc/jakarta/httpcomponents/" };

    IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm);
    connEvictor.start();//  w  ww  . j  av a 2s  . com

    for (int i = 0; i < urisToGet.length; i++) {
        String requestURI = urisToGet[i];
        HttpGet req = new HttpGet(requestURI);

        System.out.println("executing request " + requestURI);

        HttpResponse rsp = httpclient.execute(req);
        HttpEntity entity = rsp.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(rsp.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        System.out.println("----------------------------------------");

        if (entity != null) {
            entity.consumeContent();
        }
    }

    // Sleep 10 sec and let the connection evictor do its job
    Thread.sleep(20000);

    // Shut down the evictor thread
    connEvictor.shutdown();
    connEvictor.join();

    // 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:yangqi.hc.AutoRetryClientTest.java

/**
 * @param args/*from w  ww.ja v  a2 s. c  o m*/
 * @throws IOException
 * @throws ClientProtocolException
 */
public static void main(String[] args) throws ClientProtocolException, IOException {
    HttpClient client = new AutoRetryHttpClient(new ServiceUnavailableRetryStrategy() {

        private long interval = 1000;

        public boolean retryRequest(HttpResponse response, int executionCount, HttpContext context) {
            System.out.println("excute time is " + executionCount);
            if (executionCount > 4) {
                return false;
            }

            if (response.getStatusLine().getStatusCode() == 200) {
                return true;
            }
            return false;
        }

        public long getRetryInterval() {
            System.out.println("sleep " + interval);
            return interval;
        }
    });

    HttpGet get = new HttpGet("http://www.google.com");

    HttpResponse response = client.execute(get);

    System.out.println(response.getStatusLine());
}

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

public static void main(String[] args) throws Exception {
    PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
    cm.setMaxTotal(100);/*from  ww  w.  j  a v a2s .c  o  m*/

    HttpClient httpclient = new DefaultHttpClient(cm);
    try {
        // create an array of URIs to perform GETs on
        String[] urisToGet = { "http://jakarta.apache.org/", "http://jakarta.apache.org/commons/",
                "http://jakarta.apache.org/commons/httpclient/",
                "http://svn.apache.org/viewvc/jakarta/httpcomponents/" };

        IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm);
        connEvictor.start();

        for (int i = 0; i < urisToGet.length; i++) {
            String requestURI = urisToGet[i];
            HttpGet req = new HttpGet(requestURI);

            System.out.println("executing request " + requestURI);

            HttpResponse rsp = httpclient.execute(req);
            HttpEntity entity = rsp.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(rsp.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            System.out.println("----------------------------------------");

            EntityUtils.consume(entity);
        }

        // Sleep 10 sec and let the connection evictor do its job
        Thread.sleep(20000);

        // Shut down the evictor thread
        connEvictor.shutdown();
        connEvictor.join();

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

/**
 * @param args the command line arguments
 *///from  w w w  .ja  va 2s  .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.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);/*  w  w w .j ava  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();
}