Example usage for org.apache.http.client.methods HttpGet HttpGet

List of usage examples for org.apache.http.client.methods HttpGet HttpGet

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpGet HttpGet.

Prototype

public HttpGet(final String uri) 

Source Link

Usage

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);//from  w  w  w  .j  a va2 s .c o m

    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:demo.example.ClientPreemptiveDigestAuthentication.java

public static void main(String[] args) throws Exception {
    HttpHost target = new HttpHost("httpbin.org", 80, "http");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials("user", "passwd"));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {//from ww  w  . ja va  2s .c o  m

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate DIGEST scheme object, initialize it and add it to the local
        // auth cache
        DigestScheme digestAuth = new DigestScheme();
        // Suppose we already know the realm name
        digestAuth.overrideParamter("realm", "some realm");
        // Suppose we already know the expected nonce value
        digestAuth.overrideParamter("nonce", "whatever");
        authCache.put(target, digestAuth);

        // Add AuthCache to the execution context
        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd");

        System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target);
        for (int i = 0; i < 3; i++) {
            CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
            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.lxf.spider.client.ClientPreemptiveDigestAuthentication.java

public static void main(String[] args) throws Exception {
    HttpHost target = new HttpHost("localhost", 80, "http");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials("username", "password"));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {// w w w  .  java  2s .  c om

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate DIGEST scheme object, initialize it and add it to the local
        // auth cache
        DigestScheme digestAuth = new DigestScheme();
        // Suppose we already know the realm name
        digestAuth.overrideParamter("realm", "some realm");
        // Suppose we already know the expected nonce value
        digestAuth.overrideParamter("nonce", "whatever");
        authCache.put(target, digestAuth);

        // Add AuthCache to the execution context
        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        HttpGet httpget = new HttpGet("/");

        System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target);
        for (int i = 0; i < 3; i++) {
            CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                EntityUtils.consume(response.getEntity());
            } finally {
                response.close();
            }
        }
    } finally {
        httpclient.close();
    }
}

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

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

    // make sure to use a proxy that supports CONNECT
    HttpHost target = new HttpHost("issues.apache.org", 443, "https");
    HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");

    // general setup
    SchemeRegistry supportedSchemes = new SchemeRegistry();

    // Register the "http" and "https" protocol schemes, they are
    // required by the default operator to look up socket factories.
    supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    // prepare parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, true);

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, supportedSchemes);

    DefaultHttpClient httpclient = new DefaultHttpClient(ccm, params);

    httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

    HttpGet req = new HttpGet("/");

    System.out.println("executing request to " + target + " via " + 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]);
    }/*from w w w .  ja v a2  s  . co  m*/
    System.out.println("----------------------------------------");

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

    // 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:es.tsb.ltba.nomhad.example.ClientWithResponseHandler.java

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

    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient = wrapClient(httpclient);
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("A100", "123456"));

    try {/*from w  ww  .ja v  a 2s .  c om*/
        HttpGet httpget = new HttpGet(NOMHAD_URL_HEADER + "A100" + OBSERVATIONS_REQUEST);

        HttpPost httppost = new HttpPost(NOMHAD_URL_HEADER + "A100" + OBSERVATIONS_REQUEST);
        httppost.setEntity(new StringEntity(BODY_TEST));
        System.out.println("executing request " + httpget.getURI());

        // Create a response handler
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httppost, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);
        System.out.println("----------------------------------------");

    } 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:httpclient.client.ClientExecuteProxy.java

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

    // make sure to use a proxy that supports CONNECT
    HttpHost target = new HttpHost("vote.sun0769.com/include/code.asp?s=youthnet&aj=0.70161835174741", 80,
            "http");
    HttpHost proxy = new HttpHost("59.36.98.154", 80, "http");

    // general setup
    SchemeRegistry supportedSchemes = new SchemeRegistry();

    // Register the "http" and "https" protocol schemes, they are
    // required by the default operator to look up socket factories.
    supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    // prepare parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "GB2312");
    HttpProtocolParams.setUseExpectContinue(params, true);

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, supportedSchemes);

    DefaultHttpClient httpclient = new DefaultHttpClient(ccm, params);

    httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

    HttpGet req = new HttpGet("/");

    System.out.println("executing request to " + target + " via " + 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]);
    }//ww  w  .  j av a 2s.c  o  m
    System.out.println("----------------------------------------");

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

    // 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:net.modelbased.proasense.storage.registry.StorageRegistryScrapRateTestClient.java

public static void main(String[] args) {
    // Get client properties from properties file
    //        StorageRegistryScrapRateTestClient client = new StorageRegistryScrapRateTestClient();
    //        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;//  ww w .jav a2s.  c o  m

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

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

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

        // 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("MACHINE LIST: " + body);
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

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

    params = new LinkedList<NameValuePair>();
    params.add(new BasicNameValuePair("machineId", "IMM1"));

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

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

        // 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("MACHINE PROPERTIES: " + body);
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // 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", "dustParticleSensor"));

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

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

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

        // 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("PRODUCT LIST: " + body);
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

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

    params = new LinkedList<NameValuePair>();
    params.add(new BasicNameValuePair("productId", "Astra_3300"));

    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("PRODUCT PROPERTIES: " + body);
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

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

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

        // 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("MOULD LIST: " + body);
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

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

    params = new LinkedList<NameValuePair>();
    params.add(new BasicNameValuePair("productId", "Astra_3300"));

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

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

        // 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("MOULD PROPERTIES: " + body);
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

From source file:com.hilatest.httpclient.apacheexample.ClientMultiThreadedExecution.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));

    // Create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    HttpClient httpClient = new DefaultHttpClient(cm, params);

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

    // create a thread for each URI
    GetThread[] threads = new GetThread[urisToGet.length];
    for (int i = 0; i < threads.length; i++) {
        HttpGet httpget = new HttpGet(urisToGet[i]);
        threads[i] = new GetThread(httpClient, httpget, i + 1);
    }// w w  w  . j  a v a  2s .co m

    // start the threads
    for (int j = 0; j < threads.length; j++) {
        threads[j].start();
    }

    // join the threads
    for (int j = 0; j < threads.length; j++) {
        threads[j].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:httpclient.client.ClientPreemptiveDigestAuthentication.java

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

    DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient.getCredentialsProvider().setCredentials(new AuthScope("localhost", 80),
            new UsernamePasswordCredentials("username", "password"));

    BasicHttpContext localcontext = new BasicHttpContext();
    // Generate DIGEST scheme object, initialize it and stick it to 
    // the local execution context
    DigestScheme digestAuth = new DigestScheme();
    // Suppose we already know the realm name
    digestAuth.overrideParamter("realm", "some realm");
    // Suppose we already know the expected nonce value 
    digestAuth.overrideParamter("nonce", "whatever");
    localcontext.setAttribute("preemptive-auth", digestAuth);

    // Add as the first request interceptor
    httpclient.addRequestInterceptor(new PreemptiveAuth(), 0);
    // Add as the last response interceptor
    httpclient.addResponseInterceptor(new PersistentDigest());

    HttpHost targetHost = new HttpHost("localhost", 80, "http");

    HttpGet httpget = new HttpGet("/");

    System.out.println("executing request: " + httpget.getRequestLine());
    System.out.println("to target: " + targetHost);

    for (int i = 0; i < 3; i++) {
        HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
            entity.consumeContent();/*from  ww w .  j  a va  2 s.  c  om*/
        }
    }

    // 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.hilatest.httpclient.apacheexample.ClientGZipContentCompression.java

public final static void main(String[] args) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient.addRequestInterceptor(new HttpRequestInterceptor() {

        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }//from   w ww  . ja  va  2s  . c  o  m
        }

    });

    httpclient.addResponseInterceptor(new HttpResponseInterceptor() {

        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header ceheader = entity.getContentEncoding();
            if (ceheader != null) {
                HeaderElement[] codecs = ceheader.getElements();
                for (int i = 0; i < codecs.length; i++) {
                    if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }

    });

    HttpGet httpget = new HttpGet("http://www.apache.org/");

    // Execute HTTP request
    System.out.println("executing request " + httpget.getURI());
    HttpResponse response = httpclient.execute(httpget);

    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    System.out.println(response.getLastHeader("Content-Encoding"));
    System.out.println(response.getLastHeader("Content-Length"));
    System.out.println("----------------------------------------");

    HttpEntity entity = response.getEntity();

    if (entity != null) {
        String content = EntityUtils.toString(entity);
        System.out.println(content);
        System.out.println("----------------------------------------");
        System.out.println("Uncompressed size: " + content.length());
    }

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