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.android.dialer.lookup.dastelefonbuch.TelefonbuchApi.java

public static ContactInfo reverseLookup(Context context, String number) throws IOException {
    Uri uri = Uri.parse(REVERSE_LOOKUP_URL).buildUpon().appendQueryParameter("kw", number).build();
    // Cut out everything we're not interested in (scripts etc.) to
    // speed up the subsequent matching.
    String output = LookupUtils.firstRegexResult(LookupUtils.httpGet(new HttpGet(uri.toString())),
            ": Treffer(.*)Ende Treffer", true);

    String name = parseValue(output, NAME_REGEX, true, false);
    if (name == null) {
        return null;
    }/*from  w  w  w. java 2 s  .com*/

    String phoneNumber = parseValue(output, NUMBER_REGEX, false, true);
    String address = parseValue(output, ADDRESS_REGEX, true, true);

    ContactInfo info = new ContactInfo();
    info.name = name;
    info.address = address;
    info.formattedNumber = phoneNumber != null ? phoneNumber : number;
    info.website = uri.toString();

    return info;
}

From source file:org.eclipse.json.http.HttpHelper.java

public static JsonValue makeRequest(String url) throws IOException {
    long startTime = 0;
    HttpClient httpClient = new DefaultHttpClient();
    try {//from ww  w  .ja v a  2s . c om
        // Post JSON Tern doc
        HttpGet httpGet = new HttpGet(url);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity entity = httpResponse.getEntity();
        InputStream in = entity.getContent();
        // Check the status
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            // node.js server throws error
            /*
             * String message = IOUtils.toString(in); if
             * (StringUtils.isEmpty(message)) { throw new
             * TernException(statusLine.toString()); } throw new
             * TernException(message);
             */
        }

        try {
            JsonValue response = JsonValue.readFrom(new InputStreamReader(in));
            return response;
        } catch (ParseException e) {
            throw new IOException(e);
        }
    } catch (Exception e) {
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        throw new IOException(e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.igormaznitsa.zxpoly.utils.ROMLoader.java

static byte[] loadHTTPArchive(final String url) throws IOException {
    final HttpClient client = HttpClientBuilder.create().build();
    final HttpContext context = HttpClientContext.create();
    final HttpGet get = new HttpGet(url);
    final HttpResponse response = client.execute(get, context);

    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        InputStream in = null;/*w w  w . j  a va 2s  .c om*/
        try {
            final HttpEntity entity = response.getEntity();
            in = entity.getContent();
            final byte[] data = entity.getContentLength() < 0L ? IOUtils.toByteArray(entity.getContent())
                    : IOUtils.toByteArray(entity.getContent(), entity.getContentLength());
            return data;
        } finally {
            IOUtils.closeQuietly(in);
        }
    } else {
        throw new IOException("Can't download from http '" + url + "' code [" + url + ']');
    }
}

From source file:com.liferay.mobile.android.util.PortraitUtil.java

public static String downloadPortrait(Session session, String portraitURL, OutputStream os, String modifiedDate)
        throws Exception {

    String lastModified = null;/* w w  w  .java  2s . co  m*/
    InputStream is = null;

    try {
        HttpGet get = new HttpGet(portraitURL);

        if (Validator.isNotNull(modifiedDate)) {
            get.addHeader(HttpUtil.IF_MODIFIED_SINCE, modifiedDate);
        }

        HttpClient client = HttpUtil.getClient(session);
        HttpResponse response = client.execute(get);

        int status = response.getStatusLine().getStatusCode();

        if (status == HttpStatus.SC_OK) {
            is = response.getEntity().getContent();

            int count;
            byte data[] = new byte[8192];

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

            Header header = response.getLastHeader(HttpUtil.LAST_MODIFIED);
            lastModified = header.getValue();
        }
    } catch (Exception e) {
        Log.e(_CLASS_NAME, "Couldn't download portrait", e);

        throw e;
    } finally {
        close(is);
        close(os);
    }

    return lastModified;
}

From source file:com.mvn.aircraft.ApiTest.java

@Test(enabled = false)
public void testStatusCode() throws ClientProtocolException, IOException {

    HttpUriRequest request = new HttpGet("http://riiwards.com?login=bassan");

    HttpResponse httpResponse = (HttpResponse) HttpClientBuilder.create().build().execute(request);

    System.out.println("BOX: " + httpResponse.getStatus());

    Assert.assertEquals(httpResponse.getStatus(), HttpStatus.SC_OK);
    //    Assert.assertEquals("200","200");
}

From source file:org.openbaton.utils.rabbit.RabbitManager.java

public static List<String> getQueues(String brokerIp, String username, String password, int managementPort)
        throws IOException {
    List<String> result = new ArrayList<>();
    String encoding = Base64.encodeBase64String((username + ":" + password).getBytes());
    HttpGet httpGet = new HttpGet("http://" + brokerIp + ":" + managementPort + "/api/queues/");
    httpGet.setHeader("Authorization", "Basic " + encoding);

    log.trace("executing request " + httpGet.getRequestLine());
    HttpClient httpclient = HttpClients.createDefault();
    HttpResponse response = httpclient.execute(httpGet);
    HttpEntity entity = response.getEntity();

    InputStreamReader inputStreamReader = new InputStreamReader(entity.getContent());

    JsonArray array = gson.fromJson(inputStreamReader, JsonArray.class);
    if (array != null)
        for (JsonElement queueJson : array) {
            String name = queueJson.getAsJsonObject().get("name").getAsString();
            result.add(name);/* ww w.j  av a 2  s .  c o  m*/
            log.trace("found queue: " + name);
        }
    //TODO check for errors
    log.trace("found queues: " + result.toString());
    return result;
}

From source file:com.appdirect.sdk.support.HttpClientHelper.java

public static HttpGet get(String endpoint, String... params) throws URISyntaxException {
    if (params.length % 2 != 0) {
        throw new IllegalArgumentException("pass params in name=value form");
    }//from   ww w  .j  a v a2  s  . c  om

    URIBuilder builder = new URIBuilder(endpoint);
    for (int i = 0; i < params.length; i = i + 2) {
        builder.addParameter(params[i], params[i + 1]).build();
    }
    return new HttpGet(builder.build());
}

From source file:com.johnson.grab.browser.HttpClientUtil.java

/**
 * Get content by url as string/*w ww .j a  v a 2  s  . c  om*/
 * @param url
 *      original url
 * @return
 *      page content
 * @throws java.io.IOException
 */
public static String getContent(String url) throws CrawlException, IOException {
    // construct request
    HttpGet request = new HttpGet(url);
    request.setConfig(RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
            .setSocketTimeout(SOCKECT_TIMEOUT).build());
    // construct response handler
    ResponseHandler<String> handler = new ResponseHandler<String>() {
        @Override
        public String handleResponse(final HttpResponse response) throws IOException {
            StatusLine status = response.getStatusLine();
            // status
            if (status.getStatusCode() != HttpStatus.SC_OK) {
                throw new HttpResponseException(status.getStatusCode(), status.getReasonPhrase());
            }
            // get encoding in header
            String encoding = getPageEncoding(response);
            boolean encodingFounded = true;
            if (StringUtil.isEmpty(encoding)) {
                encodingFounded = false;
                encoding = UniversalConstants.Encoding.ISO_8859_1;
            }
            // get content and find real encoding
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                return null;
            }
            // get content
            byte[] contentBytes = EntityUtils.toByteArray(entity);
            if (contentBytes == null) {
                return null;
            }
            // found encoding
            if (encodingFounded) {
                return new String(contentBytes, encoding);
            }
            // attempt to discover encoding
            String rawContent = new String(contentBytes, UniversalConstants.Encoding.DEFAULT);
            Matcher matcher = PATTERN_HTML_CHARSET.matcher(rawContent);
            if (matcher.find()) {
                String realEncoding = matcher.group(1);
                if (!encoding.equalsIgnoreCase(realEncoding)) {
                    // bad luck :(
                    return new String(rawContent.getBytes(encoding), realEncoding);
                }
            }
            // not found right encoding :)
            return rawContent;
        }
    };
    // execute
    CloseableHttpClient client = HttpClientHolder.getClient();
    return client.execute(request, handler);
}

From source file:org.opencastproject.remotetest.server.resource.SearchResources.java

public static HttpResponse episode(TrustedHttpClient client, String id) throws Exception {
    return client.execute(new HttpGet(getServiceUrl() + "episode?id=" + id));
}

From source file:br.com.atmatech.auditor.webservice.WebServiceNFce.java

public String Searche(String chave) throws Exception {
    String line2;//from   w  ww  .  ja va  2  s  .  c  om
    HttpGet get = new HttpGet(
            "http://nfe.sefaz.go.gov.br/nfeweb/jsp/CConsultaCompletaNFEJSF.jsf?parametroChaveAcesso=" + chave);
    //         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    //         nameValuePairs.add(new BasicNameValuePair("rTipoDoc", "2"));

    //  HttpGet get = new HttpGet("http://homolog.sefaz.go.gov.br/nfeweb/jsp/CConsultaCompletaNFEJSF.jsf?parametroChaveAcesso=" + chave);
    HttpResponse response = client.execute(get);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line;
    File file = new File("./nfce" + new Date().getDay() + new Date().getMonth() + new Date().getYear());
    file.mkdir();
    FileWriter out = new FileWriter("./" + file + "/" + chave + ".xml");
    PrintWriter gravarArq = new PrintWriter(out);
    line2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    while ((line = rd.readLine()) != null) {
        line = line.replace("&gt;", ">").replaceAll("&lt;", "<").replace("&quot;", "\"").replace("&amp;", "&")
                .replace("&Atilde;", "");
        if (line.contains("<nfeProc xmlns=\"http://www.portalfiscal.inf.br/nfe\" versao=\"3.10\">")) {
            int index = line.indexOf("</nfeProc>");
            line2 = line2 + line.substring(0, index + 10);
            gravarArq.print(line2 + "\n");
        }
    }
    out.close();
    return line2;
}