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:com.rest.samples.getTipoCambioBanxico.java

public static void main(String[] args) {
    String url = "http://www.banxico.org.mx/tipcamb/llenarTiposCambioAction.do?idioma=sp";
    try {/* ww  w .  j av a 2  s  .  co m*/
        HttpClient hc = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(url);
        request.setHeader("User-Agent", "Mozilla/5.0");
        request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

        HttpResponse res = hc.execute(request);
        if (res.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode());
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        Document doc = Jsoup.parse(result.toString());
        Element tipoCambioFix = doc.getElementById("FIX_DATO");
        System.out.println(tipoCambioFix.text());

    } catch (IOException ex) {
        Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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

public static void main(String[] args) {

    try {/*w ww .  j a  v a  2s. co  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.javaquery.aws.elasticsearch.GetExample.java

public static void main(String[] args) {
    /**/*from  w  w w . j av  a2 s  . c  o m*/
     * Amazon ElasticSearch Service URL:
     * endpoint + / + {index_name} + / + {type} + / + {id}
     */
    String elastic_search_url = "http://xxxxx-yyyyy-r6nvlhpscgdwms5.ap-northeast-1.es.amazonaws.com/inventory/simple/123";

    /* Prepare get request */
    HttpGet httpGet = new HttpGet(elastic_search_url);
    /* Execute get request */
    httpGetRequest(httpGet);
}

From source file:httpclientsample.HttpClientSample.java

/**
 * @param args the command line arguments
 *///from w  w  w . j av  a2  s . co  m
public static void main(String[] args) throws IOException, JSONException {
    /** METHOD GET EXAMPLE **/
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet("http://localhost:8000/test/api?id=100");
    getRequest.addHeader("accept", "application/json");

    HttpResponse response = httpClient.execute(getRequest);

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

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

    String output;
    System.out.println("Response:\n");

    while ((output = br.readLine()) != null) {
        JSONObject jsonObj = new JSONObject(output);
        System.out.println("json id : " + jsonObj.get("id"));
    }

    httpClient.getConnectionManager().shutdown();
}

From source file:com.rest.samples.getReportFromJasperServer.java

public static void main(String[] args) {
    // TODO code application logic here
    String url = "http://username:password@10.49.28.3:8081/jasperserver/rest_v2/reports/Reportes/vencimientos.pdf?feini=2016-09-30&fefin=2016-09-30";
    try {//from   w w  w .  jav  a2 s.c  om
        HttpClient hc = HttpClientBuilder.create().build();
        HttpGet getMethod = new HttpGet(url);
        getMethod.addHeader("accept", "application/pdf");
        HttpResponse res = hc.execute(getMethod);
        if (res.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode());
        }

        InputStream is = res.getEntity().getContent();
        OutputStream os = new FileOutputStream(new File("vencimientos.pdf"));
        int read = 0;
        byte[] bytes = new byte[2048];

        while ((read = is.read(bytes)) != -1) {
            os.write(bytes, 0, read);
        }
        is.close();
        os.close();

        if (Desktop.isDesktopSupported()) {
            File pdfFile = new File("vencimientos.pdf");
            Desktop.getDesktop().open(pdfFile);
        }

    } catch (IOException ex) {
        Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.sim.demo.httpclient.httpget.SinaDemo.java

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

    CloseableHttpClient httpClient = HttpClients.createDefault();
    // HttpGet/*from  w ww . j  a va 2s .c  o  m*/
    HttpGet httpGet = new HttpGet("http://www.sina.com");
    System.out.println("executing request " + httpGet.getURI());
    // get
    HttpResponse response = httpClient.execute(httpGet);
    // ??
    HttpEntity entity = response.getEntity();
    // ???
    System.out.println(response.getStatusLine());
    if (entity != null) {
        // ??
        System.out.println("Response content lenght:" + entity.getContentLength());
        String content = EntityUtils.toString(entity, "UTF-8").trim();
        // HttpClient?? String?
        System.out.println("Response content:" + content);
    }
    // ?
    httpClient.close();
}

From source file:yangqi.hc.HttpContextTest.java

/**
 * @param args//from  w  ww  .  j  a v a 2  s  .c  o m
 * @throws IOException
 * @throws ClientProtocolException
 */
public static void main(String[] args) throws ClientProtocolException, IOException {
    // TODO Auto-generated method stub
    HttpClient httpclient = new DefaultHttpClient();

    HttpContext context = new BasicHttpContext();

    // Prepare a request object
    HttpGet httpget = new HttpGet("http://www.apache.org/");

    // Execute the request
    HttpResponse response = httpclient.execute(httpget, context);

    showAttr(ExecutionContext.HTTP_CONNECTION, context);
    showAttr(ExecutionContext.HTTP_PROXY_HOST, context);
    showAttr(ExecutionContext.HTTP_REQ_SENT, context);
    showAttr(ExecutionContext.HTTP_RESPONSE, context);
    showAttr(ExecutionContext.HTTP_REQUEST, context);
    showAttr(ExecutionContext.HTTP_TARGET_HOST, context);

}

From source file:yangqi.hc.HttpClientTest.java

/**
 * @param args/*from  w  ww.  j a  v a2s. c o m*/
 * @throws IOException
 * @throws ClientProtocolException
 */
public static void main(String[] args) throws ClientProtocolException, IOException {
    // TODO Auto-generated method stub
    HttpClient httpclient = new DefaultHttpClient();

    // Prepare a request object
    HttpGet httpget = new HttpGet("http://www.apache.org/");

    // Execute the request
    HttpResponse response = httpclient.execute(httpget);

    // Examine the response status
    System.out.println(response.getStatusLine());

    System.out.println(response.getLocale());

    for (Header header : response.getAllHeaders()) {
        System.out.println(header.toString());
    }

    // Get hold of the response entity
    HttpEntity entity = response.getEntity();

    System.out.println("==========entity=========");
    System.out.println(entity.getContentLength());
    System.out.println(entity.getContentType());
    System.out.println(entity.getContentEncoding());

    // If the response does not enclose an entity, there is no need
    // to worry about connection release
    if (entity != null) {
        InputStream instream = entity.getContent();
        try {

            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            // do something useful with the response
            System.out.println(reader.readLine());

        } catch (IOException ex) {

            // In case of an IOException the connection will be released
            // back to the connection manager automatically
            throw ex;

        } catch (RuntimeException ex) {

            // In case of an unexpected exception you may want to abort
            // the HTTP request in order to shut down the underlying
            // connection and release it back to the connection manager.
            httpget.abort();
            throw ex;

        } finally {

            // Closing the input stream will trigger connection release
            instream.close();

        }

        // 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.rest.samples.GetJSON.java

public static void main(String[] args) {
    // TODO code application logic here
    //        String url = "https://api.adorable.io/avatars/list";
    String url = "http://freemusicarchive.org/api/get/albums.json?api_key=60BLHNQCAOUFPIBZ&limit=5";
    try {/*from  w  ww . j a va 2 s.c  o m*/
        HttpClient hc = HttpClientBuilder.create().build();
        HttpGet getMethod = new HttpGet(url);
        getMethod.addHeader("accept", "application/json");
        HttpResponse res = hc.execute(getMethod);
        if (res.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode());
        }

        InputStream is = res.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(br);
        if (element.isJsonObject()) {
            JsonObject jsonObject = element.getAsJsonObject();
            Set<Map.Entry<String, JsonElement>> jsonEntrySet = jsonObject.entrySet();
            for (Map.Entry<String, JsonElement> entry : jsonEntrySet) {
                if (entry.getValue().isJsonArray() && entry.getValue().getAsJsonArray().size() > 0) {
                    JsonArray jsonArray = entry.getValue().getAsJsonArray();
                    Set<Map.Entry<String, JsonElement>> internalJsonEntrySet = jsonArray.get(0)
                            .getAsJsonObject().entrySet();
                    for (Map.Entry<String, JsonElement> entrie : internalJsonEntrySet) {
                        System.out.println("--->   " + entrie.getKey() + " --> " + entrie.getValue());

                    }

                } else {
                    System.out.println(entry.getKey() + " --> " + entry.getValue());
                }
            }
        }

        String output;
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

    } catch (IOException ex) {
        Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.sim.demo.httpclient.httpget.BaiduDemo.java

/**
 * @param args/*from   w ww .  j  av  a2  s .c  om*/
 * @throws IOException 
 * @throws ClientProtocolException 
 */
public static void main(String[] args) throws ClientProtocolException, IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpGet httpGet = new HttpGet("http://www.baidu.com");

    System.out.println(httpGet.getURI().toString());

    CloseableHttpResponse response = httpClient.execute(httpGet);

    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == 200) {
        HttpEntity entity = response.getEntity();

        String context = EntityUtils.toString(entity, "UTF-8");

        System.out.println("context : " + context);
    }

    httpClient.close();

}