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.gozap.chouti.service.HttpService.java

/**
 * /* www .j a  va  2s.  c o  m*/
 * @param uri uri
 * @return
 * @author saint
 * @date 2013-4-17
 */
public static byte[] get(String uri) {
    HttpClient httpClient = HttpClientFactory.getInstance();
    HttpGet httpGet = new HttpGet(uri);
    try {
        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        byte[] bytes = EntityUtils.toByteArray(httpEntity);
        return bytes;
    } catch (ClientProtocolException e) {
        LOGGER.error("get" + uri + "error", e);
    } catch (IOException e) {
        LOGGER.error("get" + uri + "error", e);
    } finally {
        httpGet.releaseConnection();
    }
    return null;
}

From source file:com.example.qrpoll.MyHttpURLConnection.java

/**
 * pobieranie zawartosci strony z serwera
 * @param url adres url strony z ktora chcemy sie polaczyc
 * @return zawartosc strony/*from   w w w. j a  v a2 s. co  m*/
 * @throws ClientProtocolException
 * @throws IOException
 * @throws Exception404 
 */
static public String get(String url) throws ClientProtocolException, IOException, Exception404 {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();

    int code = response.getStatusLine().getStatusCode();
    if (code == 404)
        throw new Exception404();

    InputStream is = entity.getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null)
        sb.append(line + "\n");

    is.close();
    String resString = sb.toString();

    return resString;
}

From source file:org.openmrs.contrib.discohub.HttpUtils.java

public static Map<String, Object> getData(String url, Header[] headers) throws IOException {
    final Map<String, Object> responseMap = new LinkedHashMap<>();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet(url);
    httpget.setHeaders(headers);//ww  w  . j  a v a 2  s. c o  m

    // 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();
                responseMap.put("headers", response.getAllHeaders());
                //System.out.println("Ratelimit attempts left: " + response.getHeaders("X-RateLimit-Remaining")[0]);
                //System.out.println("Etag = " + response.getHeaders("ETag")[0]);
                return entity != null ? EntityUtils.toString(entity) : null;
            } else if (status == 304) {
                //System.out.println("GOT 304!!!");
                return null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        }

    };
    String responseBody = httpclient.execute(httpget, responseHandler);
    responseMap.put("content", responseBody);
    return responseMap;
}

From source file:com.datatorrent.demos.mapreduce.Util.java

public static String getJsonForURL(String url) {
    HttpClient httpclient = new DefaultHttpClient();
    logger.debug(url);//w w w . j  ava2 s .c o m
    try {

        HttpGet httpget = new HttpGet(url);

        // Create a response handler
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody;
        try {
            responseBody = httpclient.execute(httpget, responseHandler);

        } catch (ClientProtocolException e) {
            logger.debug(e.getMessage());
            return null;

        } catch (IOException e) {
            logger.debug(e.getMessage());
            return null;
        } catch (Exception e) {
            logger.debug(e.getMessage());
            return null;
        }
        return responseBody.trim();
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.airbop.library.simple.AirBopImageDownloader.java

static public Bitmap downloadBitmap(String url, Context context) {
    final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
    final HttpGet getRequest = new HttpGet(url);

    try {/* www  .j  a  va2s .co  m*/
        HttpResponse response = client.execute(getRequest);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            displayMessage(context, "Error " + statusCode + " while retrieving bitmap from " + url);
            return null;
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {
                inputStream = entity.getContent();
                final Bitmap bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
                return bitmap;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                entity.consumeContent();
            }
        }
    } catch (Exception e) {
        // Could provide a more explicit error message for IOException or IllegalStateException
        getRequest.abort();
        displayMessage(context, "Error while retrieving bitmap from " + url + e.toString());
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}

From source file:lets.code.project.conectividad.ConectivityClass.java

public static String getHTMLPage() {
    String str = "***";

    try {//from  www  . j ava 2  s  .c  o m
        HttpClient hc = new DefaultHttpClient();
        //HttpPost post = new HttpPost("http://www.yahoo.com");
        HttpGet get = new HttpGet("http://barrapunto.com/index.xml");

        HttpResponse rp = hc.execute(get);
        System.out.println("STATUS " + rp.getStatusLine().getStatusCode());
        if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            str = EntityUtils.toString(rp.getEntity());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return str;
}

From source file:org.jboss.demo.loanmanagement.client.RestCommandRunner.java

/**
 * @param restCommand the command to execute (cannot be <code>null</code>)
 * @return the response as a JSON object (never <code>null</code>)
 * @throws Exception if there are problems executing the command
 */// ww w  . j  a  va  2 s. c  om
public static JSONObject run(final Command restCommand) throws Exception {
    final HttpGet httpGet = new HttpGet(restCommand.getUrl());

    { // headers
        if (restCommand.useAuthorization()) {
            httpGet.addHeader("Authorization", restCommand.geAuthorizationHeader()); //$NON-NLS-1$
        }

        httpGet.addHeader("Accept", "*/*;charset=utf-8"); //$NON-NLS-1$ //$NON-NLS-2$
    }

    final HttpClient httpClient = new DefaultHttpClient();
    InputStream is = null;

    try {
        final HttpResponse httpResponse = httpClient.execute(httpGet);

        final HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

        final BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); //$NON-NLS-1$
        final StringBuilder sb = new StringBuilder();

        String line = null;

        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }

        final String content = sb.toString();
        final JSONObject result = new JSONObject(content);

        return result;
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (final IOException e) {
                // nothing to do
            }
        }
    }
}

From source file:Tools.HttpClientUtil.java

public static String getRequest(List<KeyValuePair> paramList) {
    HttpClient client = new DefaultHttpClient();
    String paramStr = Utils.getParamsURL(paramList);

    HttpGet request = new HttpGet(Constant.SERVER_URL + Constant.LOGIN_SERVLET + paramStr);
    System.out.println("$Total Request URL:" + Constant.SERVER_URL + Constant.LOGIN_SERVLET + paramStr);
    HttpResponse response;/*  w  w  w  . j  a va2  s. c  o  m*/
    StringBuilder sb = new StringBuilder();
    try {
        response = client.execute(request);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        String line = "";
        while ((line = rd.readLine()) != null) {
            System.out.println("#" + response.getStatusLine());
            sb.append(line);
        }
    } catch (IOException ex) {
        Logger.getLogger(HttpClientUtil.class.getName()).log(Level.SEVERE, null, ex);
    }

    return sb.toString();
}

From source file:net.felixrabe.unleashthecouch.Utils.java

public static String getDocument(String couchDbDocUrl) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(couchDbDocUrl);
    HttpResponse response = null;/* w  w w.j  ava  2 s  .  c o  m*/
    try {
        response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            entity.writeTo(baos);
            return new String(baos.toByteArray(), "UTF-8");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:it.av.wikipedia.client.WikipediaClient.java

public static String Query(QueryParameters params) {
    try (CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
            .build()) {//from   w w w.java 2  s.com
        StringBuilder url = new StringBuilder(ENDPOINT);
        url.append(params.toURLQueryString());

        //System.out.println("GET: " + url);
        HttpGet request = new HttpGet(url.toString());
        request.setHeader("User-Agent", "FACWikiTool");

        // Create a custom response handler
        ResponseHandler<String> responseHandler = (final HttpResponse response) -> {
            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);
            }
        };

        return httpclient.execute(request, responseHandler);
    } catch (IOException ex) {
        Logger.getLogger(WikipediaClient.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}