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:interoperabilite.webservice.client.ClientWithRequestFuture.java

public static void main(String[] args) throws Exception {
    // the simplest way to create a HttpAsyncClientWithFuture
    HttpClient httpclient = HttpClientBuilder.create().setMaxConnPerRoute(5).setMaxConnTotal(5).build();
    ExecutorService execService = Executors.newFixedThreadPool(5);
    FutureRequestExecutionService requestExecService = new FutureRequestExecutionService(httpclient,
            execService);/*  w w w .  jav  a2s .c  o  m*/
    try {
        // Because things are asynchronous, you must provide a ResponseHandler
        ResponseHandler<Boolean> handler = new ResponseHandler<Boolean>() {
            @Override
            public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                // simply return true if the status was OK
                return response.getStatusLine().getStatusCode() == 200;
            }
        };

        // Simple request ...
        HttpGet request1 = new HttpGet("http://httpbin.org/get");
        HttpRequestFutureTask<Boolean> futureTask1 = requestExecService.execute(request1,
                HttpClientContext.create(), handler);
        Boolean wasItOk1 = futureTask1.get();
        System.out.println("It was ok? " + wasItOk1);

        // Cancel a request
        try {
            HttpGet request2 = new HttpGet("http://httpbin.org/get");
            HttpRequestFutureTask<Boolean> futureTask2 = requestExecService.execute(request2,
                    HttpClientContext.create(), handler);
            futureTask2.cancel(true);
            Boolean wasItOk2 = futureTask2.get();
            System.out.println("It was cancelled so it should never print this: " + wasItOk2);
        } catch (CancellationException e) {
            System.out.println("We cancelled it, so this is expected");
        }

        // Request with a timeout
        HttpGet request3 = new HttpGet("http://httpbin.org/get");
        HttpRequestFutureTask<Boolean> futureTask3 = requestExecService.execute(request3,
                HttpClientContext.create(), handler);
        Boolean wasItOk3 = futureTask3.get(10, TimeUnit.SECONDS);
        System.out.println("It was ok? " + wasItOk3);

        FutureCallback<Boolean> callback = new FutureCallback<Boolean>() {
            @Override
            public void completed(Boolean result) {
                System.out.println("completed with " + result);
            }

            @Override
            public void failed(Exception ex) {
                System.out.println("failed with " + ex.getMessage());
            }

            @Override
            public void cancelled() {
                System.out.println("cancelled");
            }
        };

        // Simple request with a callback
        HttpGet request4 = new HttpGet("http://httpbin.org/get");
        // using a null HttpContext here since it is optional
        // the callback will be called when the task completes, fails, or is cancelled
        HttpRequestFutureTask<Boolean> futureTask4 = requestExecService.execute(request4,
                HttpClientContext.create(), handler, callback);
        Boolean wasItOk4 = futureTask4.get(10, TimeUnit.SECONDS);
        System.out.println("It was ok? " + wasItOk4);
    } finally {
        requestExecService.close();
    }
}

From source file:com.hsbc.frc.SevenHero.ClientProxyAuthentication.java

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

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*from  ww  w.  j av a2 s.c  o  m*/
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080),
                new UsernamePasswordCredentials("43668069", "wf^O^2013"));

        HttpHost targetHost = new HttpHost("pt.3g.qq.com");
        HttpHost proxy = new HttpHost("133.13.162.149", 8080);

        BasicClientCookie netscapeCookie = null;

        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        // httpclient.getCookieStore().addCookie(netscapeCookie);
        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        HttpGet httpget = new HttpGet("/");
        httpget.addHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");

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

        HttpResponse response = httpclient.execute(targetHost, httpget);

        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());

        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        InputStream is = entity.getContent();
        StringBuffer sb = new StringBuffer(200);
        byte data[] = new byte[65536];
        int n = 1;
        do {
            n = is.read(data);
            if (n > 0) {
                sb.append(new String(data));
            }
        } while (n > 0);

        // System.out.println(sb);
        EntityUtils.consume(entity);

        System.out.println("----------------------------------------");
        Header[] headerlist = response.getAllHeaders();
        for (int i = 0; i < headerlist.length; i++) {
            Header header = headerlist[i];
            if (header.getName().equals("Set-Cookie")) {
                String setCookie = header.getValue();
                String cookies[] = setCookie.split(";");
                for (int j = 0; j < cookies.length; j++) {
                    String cookie[] = cookies[j].split("=");
                    CookieManager.cookie.put(cookie[0], cookie[1]);
                }
            }
            System.out.println(header.getName() + ":" + header.getValue());
        }
        String sid = getSid(sb.toString(), "&");
        System.out.println("sid: " + sid);

        httpclient = new DefaultHttpClient();
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080),
                new UsernamePasswordCredentials("43668069", "wf^O^2013"));
        String url = Constant.openUrl + "&" + sid;
        targetHost = new HttpHost(url);

        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        httpget = new HttpGet("/");
        httpget.addHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        Iterator it = CookieManager.cookie.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            netscapeCookie = new BasicClientCookie((String) (key), (String) (value));
            netscapeCookie.setVersion(0);
            netscapeCookie.setDomain(".qq.com");
            netscapeCookie.setPath("/");
            // httpclient.getCookieStore().addCookie(netscapeCookie);
        }

        response = httpclient.execute(targetHost, httpget);

    } 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:org.slieer.http.auth.ClientPreemptiveBasicAuthentication.java

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

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

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*from  w  w w  . j a  va 2s  .  co m*/
        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials("newuser", "tomcat"));

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local
        // auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        // Add AuthCache to the execution context
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        HttpGet httpget = new HttpGet("/simpleweb/protected");

        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());
            }
            EntityUtils.consume(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:com.dlmu.heipacker.crawler.client.ClientPreemptiveBasicAuthentication.java

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

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

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/* w  w  w  .ja  v  a 2s .c  o  m*/
        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials("username", "password"));

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local
        // auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        // Add AuthCache to the execution context
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        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());
            }
            EntityUtils.consume(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:com.wolfsoftco.httpclient.RestClient.java

@SuppressWarnings("resource")
public static void main(String[] args) {
    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    try {//from  w w w . ja  va 2 s.  c om
        HttpEntity entity = null;
        String responseHtml = null;
        httpclient = HttpClients.custom().build();

        //Based on CURL line:
        //curl localhost:9090/oauth/token -d "grant_type=password&scope=write&username=greg&password=turnquist" -u foo:bar

        //clientid:secret
        String clientID = "foo:bar";

        HttpUriRequest login = RequestBuilder.post().setUri(new URI(URL))
                .addHeader("Authorization", "Basic " + Base64.encodeBase64String(clientID.getBytes()))
                .addParameter("grant_type", "password").addParameter("scope", "read")
                .addParameter("username", "greg").addParameter("password", "turnquist").build();

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

        responseHtml = EntityUtils.toString(entity);
        EntityUtils.consume(entity);

        JsonObject jsonObject = null;
        String token = null;
        if (responseHtml.startsWith("{")) {
            JsonParser parser = new JsonParser();
            jsonObject = parser.parse(responseHtml).getAsJsonObject();
            token = jsonObject.get("access_token").getAsString();
        }

        if (token != null) {
            HttpGet request = new HttpGet(URL_FLIGHTS);
            request.addHeader("Authorization", "Bearer " + token);

            response = httpclient.execute(request);
            entity = response.getEntity();
            responseHtml = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
            System.out.println(responseHtml);

        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {

            if (httpclient != null)
                httpclient.close();
            if (response != null)
                response.close();

        } catch (IOException e) {
        }
    }
}

From source file:com.work.common.demo.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream instream = new FileInputStream(new File("d:\\googlemap.keystore"));
    try {/*from   w  ww.jav  a2  s.  c o m*/
        trustStore.load(instream, "111111".toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
            .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpGet httpget = new HttpGet(
                "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=AIzaSyBR0i9RL44iG8IUx9LcCgxsYOJf6FutQhE");

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

        CloseableHttpResponse response = httpclient.execute(httpHost, httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                System.out.println(EntityUtils.toString(entity));
            }
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:adapter.tdb.sync.clients.GetVocabularyOfMagicDrawAdapterAndPushToStore.java

public static void main(String[] args) {

    Thread thread = new Thread() {
        public void start() {

            URI vocabURI = URI.create("http://localhost:8080/oslc4jmagicdraw/services/sysml-rdfvocabulary");

            // create an empty RDF model
            Model model = ModelFactory.createDefaultModel();

            // use FileManager to read OSLC Resource Shape in RDF
            //            String inputFileName = "file:C:/Users/Axel/git/EcoreMetamodel2OSLCSpecification/EcoreMetamodel2OSLCSpecification/Resource Shapes/Block.rdf";
            //            String inputFileName = "file:C:/Users/Axel/git/ecore2oslc/EcoreMetamodel2OSLCSpecification/RDF Vocabulary/sysmlRDFVocabulary of OMG.rdf";
            //            InputStream in = FileManager.get().open(inputFileName);
            //            if (in == null) {
            //               throw new IllegalArgumentException("File: " + inputFileName
            //                     + " not found");
            //            }

            // create TDB dataset
            String directory = TriplestoreUtil.getTriplestoreLocation();
            Dataset dataset = TDBFactory.createDataset(directory);
            Model tdbModel = dataset.getDefaultModel();
            try {

                HttpGet httpget = new HttpGet(vocabURI);
                httpget.addHeader("accept", "application/rdf+xml");
                CloseableHttpClient httpClient = HttpClients.createDefault();
                HttpResponse response = httpClient.execute(httpget);
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    InputStream inputStream = entity.getContent();
                    model.read(inputStream, null);
                    tdbModel.add(model);
                }//from w w  w  .j  a  v  a2s .  c o  m

            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            tdbModel.close();
            dataset.close();
        }
    };
    thread.start();
    try {
        thread.join();
        System.out.println("Vocabulary of OSLC MagicDraw SysML adapter added to triplestore");
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:demo.example.ClientPreemptiveBasicAuthentication.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.j a v  a 2 s . com*/

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local
        // auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(target, basicAuth);

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

        HttpGet httpget = new HttpGet("http://httpbin.org/hidden-basic-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.ClientPreemptiveBasicAuthentication.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 {/*  ww w. j  av a 2 s.co  m*/

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local
        // auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(target, basicAuth);

        // 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: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;//from w ww.  j av  a2 s. 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 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());
    }
}