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:HelloWorld.HelloWorldTest.java

@Test
public void getPeopleTest() throws URISyntaxException, IOException {
    URI uri = new URI(baseURI + "api/person");
    HttpGet get = new HttpGet(uri);
    CloseableHttpResponse response = client.execute(get);

    assertEquals(200, response.getStatusLine().getStatusCode());

    Person[] people = responseToEntity(response, Person[].class);
    assertEquals("Joe", people[0].firstName);
}

From source file:com.huguesjohnson.retroleague.util.HttpFetch.java

public static InputStream fetch(String address, int timeout) throws MalformedURLException, IOException {
    HttpGet httpRequest = new HttpGet(URI.create(address));
    HttpClient httpclient = new DefaultHttpClient();
    final HttpParams httpParameters = httpclient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeout);
    HttpConnectionParams.setSoTimeout(httpParameters, timeout);
    HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
    HttpEntity entity = response.getEntity();
    BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
    InputStream instream = bufHttpEntity.getContent();
    return (instream);
}

From source file:org.addhen.smssync.net.SmsSyncHttpClient.java

public static HttpResponse GetURL(String URL) throws IOException {

    try {//  w ww .  java  2  s  .  c  o  m
        // wrap try around because this constructor can throw Error
        final HttpGet httpget = new HttpGet(URL);
        httpget.addHeader("User-Agent", "SmsSync-Android/1.0)");

        // Post, check and show the result (not really spectacular, but
        // works):
        HttpResponse response = httpclient.execute(httpget);

        return response;

    } catch (final Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:eltharis.wsn.showIDActivity.java

private String executeGET(int id) throws Exception {
    HttpClient httpclient = new DefaultHttpClient(); //tutaj jest podobnie jak w showAllActivity
    HttpResponse response = httpclient/*w w w  .ja va  2s  . c  om*/
            .execute(new HttpGet("https://agile-depths-5530.herokuapp.com/usershow/" + Integer.toString(id)));
    StatusLine statusline = response.getStatusLine();
    Toast toast = Toast.makeText(getApplicationContext(),
            "HTTP Response: " + Integer.toString(statusline.getStatusCode()), Toast.LENGTH_LONG);
    toast.show();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    response.getEntity().writeTo(out);
    String responseString = out.toString();
    out.close();
    return responseString;
}

From source file:com.aws.sampleImage.url.TestHttpGetFlickrAPI.java

private static String callFlickrAPIForEachKeyword(String query) throws IOException, JSONException {
    String apiKey = "ad4f88ecfd53b17f93178e19703fe00d";
    String apiSecret = "96cab0e9f89468d6";

    int totalPages = 4;

    int total = 500;
    int perPage = 500;

    int counter = 0;

    int currentCount = 0;

    for (int i = 1; i <= totalPages && currentCount <= total; i++, currentCount = currentCount + perPage) {

        String url = "https://api.flickr.com/services/rest/?method=flickr.photos.search&text=" + query
                + "&extras=url_c,url_m,url_n,license,owner_name&per_page=500&page=" + i
                + "&format=json&api_key=" + apiKey + "&api_secret=" + apiSecret + "&license=4,5,6,7,8";

        System.out.println("URL FORMED --> " + url);

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

        System.out.println("GET Response Status:: " + httpResponse.getStatusLine().getStatusCode());

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(httpResponse.getEntity().getContent()));

        String inputLine;/*from   ww w.j ava  2  s.c  om*/
        StringBuffer response = new StringBuffer();

        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();

        String responseString = response.toString();

        responseString = responseString.replace("jsonFlickrApi(", "");

        int length = responseString.length();

        responseString = responseString.substring(0, length - 1);

        // print result
        System.out.println("After making it a valid JSON --> " + responseString);
        httpClient.close();

        JSONObject json = null;
        try {
            json = new JSONObject(responseString);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //System.out.println("Converted JSON String " + json);

        JSONObject photosObj = json.has("photos") ? json.getJSONObject("photos") : null;
        total = photosObj.has("total") ? (Integer.parseInt(photosObj.getString("total"))) : 0;
        perPage = photosObj.has("perpage") ? (Integer.parseInt(photosObj.getString("perpage"))) : 0;

        System.out.println(" perPage --> " + perPage + " total --> " + total);

        JSONArray photoArr = photosObj.getJSONArray("photo");
        System.out.println("Length of Array --> " + photoArr.length());
        String scrapedImageURL = "";

        for (int itr = 0; itr < photoArr.length(); itr++) {
            JSONObject tempObject = photoArr.getJSONObject(itr);
            scrapedImageURL = tempObject.has("url_c") ? tempObject.getString("url_c")
                    : tempObject.has("url_m") ? tempObject.getString("url_m")
                            : tempObject.has("url_n") ? tempObject.getString("url_n") : "";

            //System.out.println("Scraped Image URL --> " + scrapedImageURL);

            counter++;
        }

    }

    System.out.println("C O U N T E R -> " + counter);
    return null;
}

From source file:com.elastic.support.diagnostics.RestModule.java

public String submitRequest(String url) {

    HttpResponse response = null;//from w w w  .j  a  v  a  2s  . com
    String result = "";
    try {
        HttpGet httpget = new HttpGet(url);
        response = client.execute(httpget);
        try {
            org.apache.http.HttpEntity entity = response.getEntity();
            if (entity != null) {
                checkResponseCode(url, response);
                result = EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            logger.error("Error handling response for " + url, e);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } catch (HttpHostConnectException e) {
        throw new RuntimeException("Error connecting to host " + url, e);
    } catch (Exception e) {
        if (e.getMessage().contains("401 Unauthorized")) {
            logger.error("Auth failure", e);
            throw new RuntimeException("Authentication failure: invalid login credentials.", e);
        } else {
            logger.error("Diagnostic query: " + url + "failed.", e);
        }
    }

    return result;

}

From source file:com.webbfontaine.valuewebb.action.tt.dataimporter.TTMergeTest.java

@Test(parameters = "daiTTURL")
public void testTTMerge(String daiTTURL) throws Exception {

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpUriRequest httpGet = new HttpGet(daiTTURL);

    HttpResponse response = httpClient.execute(httpGet);

    assert response.getStatusLine().getStatusCode() == 200;

    TtGen daiTT = (TtGen) Doc2Bytes.unmarshal(response.getEntity().getContent(), TtGen.class);
    assert daiTT != null;

    TtGen ttGen = getTT();/*  w ww  .  j  a  va2  s  . co m*/
    MergeLoadedTT.merge(daiTT, ttGen);
    assert ttGen.getAppTin().equals(daiTT.getAppTin());
    assert !ttGen.getAppAdr().isEmpty(); // keep original

    assert ttGen.getFirstTtInvs().getInvCur().equals(daiTT.getFirstTtInvs().getInvCur());
    assert ttGen.getFirstTtInvs().getInsuranceF() != null; // keep original

    Pd pd = ttGen.getFirstTtInvs().getPds().get(0);
    Pd daiPD = daiTT.getFirstTtInvs().getPds().get(0);
    assert pd.getCtyOrig().equals(daiPD.getCtyOrig());
    assert pd.getHsCodeD().equals(daiPD.getHsCodeD());
}

From source file:com.alta189.cyborg.factoids.util.HTTPUtil.java

public static String readRandomLine(String url) {
    HttpGet request = new HttpGet(url);
    HttpClient httpClient = new DefaultHttpClient();
    try {/*w  w w .j a  v  a2 s . co  m*/
        HttpResponse response = httpClient.execute(request);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        List<String> lines = new ArrayList<String>();
        String line = "";
        while ((line = rd.readLine()) != null) {
            lines.add(line);
        }

        if (lines.size() > 1) {
            int i = randomNumber(0, lines.size() + 1);
            return lines.get(i);
        } else if (lines.size() == 1) {
            return lines.get(0);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.xwiki.contrib.repository.npm.internal.utils.NpmHttpUtils.java

public static InputStream performGet(URI uri, HttpClientFactory httpClientFactory, HttpContext localContext,
        Header[] headers) throws HttpException {
    HttpGet getMethod = new HttpGet(uri);
    getMethod.setHeaders(headers);/* www  .j  a  v a  2 s .co m*/
    CloseableHttpClient httpClient = httpClientFactory.createClient(null, null);
    CloseableHttpResponse response;
    try {
        if (localContext != null) {
            response = httpClient.execute(getMethod, localContext);
        } else {
            response = httpClient.execute(getMethod);
        }
    } catch (Exception e) {
        throw new HttpException(String.format("Failed to request [%s]", getMethod.getURI()), e);
    }

    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_OK) {
        try {
            return response.getEntity().getContent();
        } catch (IOException e) {
            throw new HttpException(
                    String.format("Failed to parse response body of request [%s]", getMethod.getURI()), e);
        }
    } else {
        throw new HttpException(String.format("Invalid answer [%s] from the server when requesting [%s]",
                response.getStatusLine().getStatusCode(), getMethod.getURI()));
    }
}

From source file:nl.mineleni.cbsviewer.jsp.VersieJSPIntegrationTest.java

/**
 * testcase voor versie.jsp./*ww  w .j a  va  2 s  .  c  o m*/
 * 
 * @todo kijken of we de integratie tests tegen de echte war kunnen laten
 *       draaien
 * @throws Exception
 */
@Override
@Test
@Ignore("Mislukt vooralsnog omdat het bestand met versie informatie (/META-INF/MANIFEST.MF) niet gevonden kan worden.")
public void testIfValidResponse() throws Exception {
    response = client.execute(new HttpGet(BASE_TEST_URL + "versie.jsp"));
    assertThat("Response status is OK.", response.getStatusLine().getStatusCode(), equalTo(SC_OK));

    boilerplateValidationTests(response);
}