Android HttpGet - top ranked examples from Open Source projects

These code examples were ranked by Codota’s semantic indexing as the best open source examples for Android HttpGet class.

This code example shows how to use the following methods:
  void retrieveSupplementalInfo() throws IOException, InterruptedException { 
 
    String encodedProductID = URLEncoder.encode(productID, "UTF-8");
    String uri = BASE_PRODUCT_URI + encodedProductID;
 
    HttpUriRequest head = new HttpGet(uri);
    AndroidHttpClient client = AndroidHttpClient.newInstance(null);
    HttpResponse response = client.execute(head);
    int status = response.getStatusLine().getStatusCode();
    if (status != 200) {
      return; 
    } 
 
    String content = consume(response.getEntity());
    Matcher matcher = PRODUCT_NAME_PRICE_PATTERN.matcher(content);
    if (matcher.find()) {
      append(matcher.group(1));
      append(matcher.group(2));
    } 
    setLink(uri);
9
CodeRank
This code example shows how to use the following methods:
		if (uri.indexOf("http://") == -1)
			uri = "http://" + uri;
		boolean reached = isAvailable();
		try { 
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpGet httpget = new HttpGet(uri);
			httpclient.execute(httpget);			
		} catch (Exception e) { 
			reached = false;
		} 
		return reached;
	} 
	 
	 
} 
8
CodeRank
This code example shows how to use the following methods:addHeader, getParams
        if (DEBUG) Log.d(TAG, "Downloading XTRA data from " + url);
 
        AndroidHttpClient client = null;
        try { 
            client = AndroidHttpClient.newInstance("Android");
            HttpUriRequest req = new HttpGet(url);
 
            if (isProxySet) {
                HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                ConnRouteParams.setDefaultProxy(req.getParams(), proxy);
            } 
 
            req.addHeader(
                    "Accept", 
                    "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic"); 
 
            req.addHeader(
                    "x-wap-profile", 
                    "http://www.openmobilealliance.org/tech/profiles/UAPROF/ccppschema-20021212#"); 
 

8
CodeRank
This code example shows how to use the following methods:
        } 
 
        @Override 
        public HttpResponse call() throws Exception {
            try { 
                return client.execute(new HttpGet(url));
            } finally { 
                client.getConnectionManager().closeExpiredConnections();
            } 
        } 
    } 
} 
8
CodeRank
This code example shows how to use the following methods:
     * @param graceTime 
     * @return 
     * @throws IOException 
     */ 
    public static HttpResponse tryGet(final HttpClient client, final String url, final long graceTime) throws IOException {
        return tryGet(client, new HttpGet(url));
    } 
 
    /** 
     * Tries a get on the provided client consuming the request body. 
     * 
     * @param client 
     * @param url 
     * @return response body as string 
     * @throws IOException 
     */ 
    public static String tryGetAndConsume(final HttpClient client, final String url) throws IOException {
        // Get the response 
        HttpResponse response = tryGet(client, url);
 
8
CodeRank
This code example shows how to use the following methods:
        try { 
            HttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setSoTimeout(httpParams, SOCKET_TIMEOUT);
            HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);
            HttpClient httpClient = new DefaultHttpClient(httpParams);
            HttpGet httpget = new HttpGet(TIMER_URL);
            HttpResponse response = httpClient.execute(httpget);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                time = Long.parseLong(EntityUtils.toString(entity),10);
                logger.debug("Got remote timestamp {}", time);
            } 
        } catch (IOException e) {
            logger.warn("Error obtaining the synchronized remote timestamp, defaulting to the local one",e);
        } 
         
        if (time == -1) {
            time = System.currentTimeMillis();
        } 
         
7
CodeRank
This code example shows how to use the following methods:
        } 
 
        ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY),
                new UsernamePasswordCredentials(user, pass));
 
        HttpGet get = new HttpGet(url);
        HttpResponse hr;
        try { 
            hr = httpClient.execute(get);
        } catch (Exception e) {
            if (responseSubstring == null)
                return false; 
            else // in case substring is defined, rethrow exception so, we can easier analyze the cause 
                throw new Exception(e);
        } 
 
        int statusCode = hr.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            log.info("statusCode not expected. statusCode=" + statusCode + ", URL=" + url);
            return false; 
8
CodeRank
This code example shows how to use the following methods:
   @RunAsClient 
   @Test 
   public void servletDatasourceInjectionTest(){ 
      DefaultHttpClient httpclient = new DefaultHttpClient();
      HttpResponse response;
      HttpGet httpget = new HttpGet(baseURL.toString());
 
      String responseText;
      try { 
         response = httpclient.execute(httpget);
         HttpEntity entity = response.getEntity();
         responseText = EntityUtils.toString(entity);
      } catch (IOException ex) {
         throw new RuntimeException("No response from servlet!", ex);
      } 
 
      assertTrue("Masked datasource not injected correctly to the servlet! Servlet response text: " + responseText, responseText.contains("true"));
   } 
 
} 
8
CodeRank
This code example shows how to use the following methods:
            Log.e(LOG_TAG, "path=" + dirRelativePath + " recurse=" + recurse + " mode=" +
                    modeString, e);
            return new LinkedList<String>();
        } 
 
        HttpGet httpRequest = new HttpGet(url.toString());
        ResponseHandler<LinkedList<String>> handler = new ResponseHandler<LinkedList<String>>() {
            @Override 
            public LinkedList<String> handleResponse(HttpResponse response)
                    throws IOException { 
                LinkedList<String> lines = new LinkedList<String>();
 
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    return lines;
                } 
                HttpEntity entity = response.getEntity();
                if (entity == null) {
                    return lines;
                } 
 

8
CodeRank
This code example shows how to use the following methods:addHeader, getParams
        if (DEBUG) Log.d(TAG, "Downloading XTRA data from " + url);
 
        AndroidHttpClient client = null;
        try { 
            client = AndroidHttpClient.newInstance("Android");
            HttpUriRequest req = new HttpGet(url);
 
            if (isProxySet) {
                HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                ConnRouteParams.setDefaultProxy(req.getParams(), proxy);
            } 
 
            req.addHeader(
                    "Accept", 
                    "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic"); 
 
            req.addHeader(
                    "x-wap-profile", 
                    "http://www.openmobilealliance.org/tech/profiles/UAPROF/ccppschema-20021212#"); 
 

7
CodeRank
This code example shows how to use the following methods:setHeader, x 1
 
        CloseableHttpClient httpclient = HttpClients.createDefault();
 
        String leagueUrl = "http://www.okooo.com/soccer/league/";
 
        HttpGet request = new HttpGet(leagueUrl);
        request
            .setHeader("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); 
        request
            .setHeader(
                "User-Agent", 
                "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"); 
        request.setHeader("DNT", "1");
        request.setHeader("Accept-Encoding", "gzip,deflate,sdch");
        request.setHeader("Accept-Language",
            "zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4,ko;q=0.2,zh-TW;q=0.2"); 
 
        return httpclient.execute(request);
    } 

7
CodeRank
This code example shows how to use the following methods:setHeader
	} 
 
	public InputStreamReader callGet(String url)
			throws ServiceNotAvailableException, ClientProtocolException, 
			IOException { 
		mSERVERGET = new HttpGet(url);
 
		mSERVERGET.setHeader("Cookie", getSession());
		HttpResponse response = mClient.execute(mSERVERGET);
		InputStream is = response.getEntity().getContent();
		InputStreamReader isr = new InputStreamReader(is, "UTF-8");
		return isr;
 
	} 
 
	/* 
	 * private void systemConnect() throws ServiceNotAvailableException { // 
	 * Cloud server hand shake String uri = mENDPOIN + "system/connect"; 
	 * mSERVERPOST = new HttpPost(uri); try { HttpResponse response = 
	 * mClient.execute(mSERVERPOST); InputStream result = 
7
CodeRank
This code example shows how to use the following methods:
 
  @Test 
  public void testExecute() throws IOException { 
    AndroidHttpClient client = AndroidHttpClient.newInstance("foo");
    Robolectric.addPendingHttpResponse(200, "foo"); 
    HttpResponse resp = client.execute(new HttpGet("/foo"));
    assertThat(resp.getStatusLine().getStatusCode()).isEqualTo(200);
    assertThat(Strings.fromStream(resp.getEntity().getContent())).isEqualTo("foo");
  } 
} 
7
CodeRank
This code example shows how to use the following methods:setHeader
        HttpClient client = HttpClientBuilder.create().build();
 
        try { 
            LOGGER.info("Fetching latest version number of eHour release from " + versionUrl);
 
            HttpGet request = new HttpGet(versionUrl);
            request.setHeader("User-Agent", String.format("%s eHour update client v%s", isScheduled ? "Scheduled" : "Bootstrap", currentVersion));
 
            BasicResponseHandler responseHandler = new BasicResponseHandler();
            String response = client.execute(request, responseHandler);
 
            return Optional.of(response);
        } catch (Exception e) {
            LOGGER.info("Failed to retrieve latest published eHour version: " + e.getMessage());
 
        } 
 
        return Optional.absent(); 
    } 
} 
7
CodeRank
This code example shows how to use the following methods:
		} 
        return false; 
	} 
 
	private InputStream getUrl(String url) throws Exception {
		HttpGet request = new HttpGet(url);
		HttpResponse response = executeRequest(request);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			InputStream instream = entity.getContent();
            return instream;
		} 
		return null; 
	} 
 
    private void putUrl(String url, String data) throws Exception {
        HttpPut put = new HttpPut(url);
        put.setEntity(new StringEntity(data));
        HttpResponse response = executeRequest(put);
    } 
8
CodeRank
This code example shows how to use the following methods:abort, getURI
public class ClientAbortMethod { 
 
    public final static void main(String[] args) throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        try { 
            HttpGet httpget = new HttpGet("http://www.apache.org/");
 
            System.out.println("executing request " + httpget.getURI());
            HttpResponse response = httpclient.execute(httpget);
            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("----------------------------------------");
 
            // Do not feel like reading the response body 
            // Call abort on the request object 

6
CodeRank
This code example shows how to use the following methods:
		Log.d(TAG, "Returning value:" + success);
		return success;
	} 
 
	public String sendGet(String url) {
		httpGet = new HttpGet(url);
 
		try { 
			response = httpClient.execute(httpGet);
		} catch (Throwable e) {
			Log.e(TAG, "sendGet exception: ", e);
		} 
 
		// we assume that the response body contains the error message 
		try { 
			if (null == response)
				return null; 
			ret = EntityUtils.toString(response.getEntity());
		} catch (Throwable e) {
			Log.e(TAG, "sendGet exception: ", e);
7
CodeRank
This code example shows how to use the following methods:
    assertEquals(FILE_CONTENTS, body.getText());
  } 
 
  private void assertUrlHasContentType(String url, String appcacheMimeType) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);
    HttpResponse response;
 
    try { 
      response = httpclient.execute(httpget);
    } catch (Throwable t) {
      throw Throwables.propagate(t);
    } 
 
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    assertEquals(1, contentTypeHeaders.length);
    assertTrue(contentTypeHeaders[0].getValue().contains(appcacheMimeType));
  } 
} 
8
CodeRank
This code example shows how to use the following methods:setHeader
		try { 
			// It prepares the URL 
			String path = "/" + encode(URL) + "/" + encode(Content) + "/" + webInner;
			URI getURI = new URI("https", serverURL, path, null);
			String getURL = getURI.toString();
			HttpGet httpget = new HttpGet(getURL);
			httpget.setHeader("X-Api-Key", apikey);
			httpget.setHeader("X-Api-Version", "1.0.0");
			threadpool.submit(new AsyncHttpRequest(httpclient, localContext, httpget, cache, getURL, responseHandler));
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} 
	} 
	 
	// Encode all characters 
	private String encode(String s) {
		s = Uri.encode(s);
		s = s.replace("(", "%28");
	    s = s.replace(")", "%29");
	    s = s.replace("!", "%21");
6
CodeRank
This code example shows how to use the following methods:setHeader
 
  public String search(String url) throws Exception {
 
    leniency(); 
 
    HttpGet get = new HttpGet(url);
    setUserAgent(get);
    get.setHeader("Content-Encoding", "application/x-www-form-encoded");
    HttpResponse response = getHttpClient().execute(get);
 
    String string;
    Reader reader = new InputStreamReader(response.getEntity().getContent(), "UTF8");
    try { 
      string = IOUtils.toString(reader);
    } finally { 
      reader.close();
    } 
 
    return string;
 
6
CodeRank
This code example shows how to use the following methods:setParams
	} 
 
	private Bitmap downloadImage(String... urls) {
		HttpClient httpClient = CustomHttpClient.getHttpClient();
		try { 
			HttpGet request = new HttpGet(urls[0]);
			HttpParams params = new BasicHttpParams();
			HttpConnectionParams.setSoTimeout(params, 60000); // 1 minute
			request.setParams(params);
			HttpResponse response = httpClient.execute(request);
			byte[] image = EntityUtils.toByteArray(response.getEntity());
			Bitmap mBitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
			return mBitmap;
		} 
		catch (IOException e) {
		} 
		return null; 
	} 
} 
6
CodeRank
This code example shows how to use the following methods:abort, getURI
public class ClientConnectionRelease { 
 
    public final static void main(String[] args) throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        try { 
            HttpGet httpget = new HttpGet("http://www.apache.org/");
 
            // Execute HTTP request 
            System.out.println("executing request " + httpget.getURI());
            HttpResponse response = httpclient.execute(httpget);
 
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println("----------------------------------------");
 
            // Get hold of the response entity 
            HttpEntity entity = response.getEntity();
 
            // If the response does not enclose an entity, there is no need 
            // to bother about connection release 

6
CodeRank
This code example shows how to use the following methods:addHeader, getParams
        if (Config.LOGD) Log.d(TAG, "Downloading XTRA data from " + url);
 
        AndroidHttpClient client = null;
        try { 
            client = AndroidHttpClient.newInstance("Android");
            HttpUriRequest req = new HttpGet(url);
 
            if (isProxySet) {
                HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                ConnRouteParams.setDefaultProxy(req.getParams(), proxy);
            } 
 
            req.addHeader(
                    "Accept", 
                    "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic"); 
 
            req.addHeader(
                    "x-wap-profile", 
                    "http://www.openmobilealliance.org/tech/profiles/UAPROF/ccppschema-20021212#"); 
 

6
CodeRank
This code example shows how to use the following methods:sleep
	private static HttpClient client = AndroidHttpClient.newInstance("ThemeBuilder");
 
	public static InputStream downloadData(String url) throws IOException {
 
		InputStream is = null;
		HttpGet get = new HttpGet(url);
 
		try { 
			HttpResponse response = client.execute(get);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		} catch (ClientProtocolException cpe) {
			cpe.printStackTrace();
		} catch (IOException ioe) {
			try { 
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} 
			HttpResponse response = client.execute(get);

7
CodeRank
This code example shows how to use the following methods:addHeader
import org.apache.http.client.methods.HttpGet; 
 
public class UriRead extends UriHttp { 
 
	public UriRead(URI uri) throws HttpException, IOException {
		HttpGet httpGet = new HttpGet(uri.toASCIIString());
		httpGet.addHeader("Connection", "close");
		execute(httpGet);
	} 
 
} 
6
CodeRank
This code example shows how to use the following methods:abort
 
  @Override 
  protected  DailyResponse doInBackground(Object... is) {
    HttpClient httpclient = new DefaultHttpClient();
    String url = Util.getHarvestBase(context) + "/daily";
    HttpRequestBase requestBase = new HttpGet(url);
    Util.addBasicAuthAndHarvestHeaders(context, requestBase);
    try { 
      HttpResponse httpResponse = httpclient.execute(requestBase);
      String content = Util.getContentFromHttpResponse(httpResponse);
      DailyResponse dailyResponse = Util.getGson().fromJson(content, DailyResponse.class);
      return dailyResponse;
    } catch (Exception e) {
      requestBase.abort();
      Log.e(TAG, e.getMessage(), e);
    } 
    return null; 
  } 
   
  @Override 
6
CodeRank
This code example shows how to use the following methods:
			url += URLEncodedUtils.format(params, "UTF-8");
		} 
 
		Log.i("Request URL: " + url);
 
		return doRequest(new HttpGet(url), responseHandler);
	} 
 
	protected <T> T doPost(String url, List<NameValuePair> params, ResponseHandler<T> responseHandler) {
		HttpPost request = new HttpPost(url);
		HttpEntity entity;
 
		try { 
			entity = new UrlEncodedFormEntity(params, "UTF-8");
		} 
		catch (UnsupportedEncodingException e) {
			Log.e("Couldn't encode params", e);
			return null; 
		} 
 
7
CodeRank
This code example shows how to use the following methods:addHeader
   		JSONObject json = null;
	    
   		try { 
   			HttpGet httpRequest = null;
 
   			httpRequest = new HttpGet(url.toURI());
   			httpRequest.addHeader("Content-type", "application/json");
   			httpRequest.addHeader("Accept", "application/json");
   			httpRequest.addHeader("Authorization", "MediaTemple " + apiKey);
   			httpRequest.addHeader("Referer", "http://android.syrinxoon.net/p/mt-account-center.html");
   			httpRequest.addHeader("User-Agent", "MtAccountCenter-Android/" + userAgentVersion);
 
   			HttpClient httpClient = new DefaultHttpClient();
   			HttpResponse response = (HttpResponse) httpClient.execute(httpRequest);
 
   			HttpEntity entity = response.getEntity();
   			BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
   			InputStream input = bufHttpEntity.getContent();
        
   			// Check if task has been interrupted 
6
CodeRank
This code example shows how to use the following methods:setParams
	} 
 
	private Bitmap downloadImage(String... urls) {
		HttpClient httpClient = CustomHttpClient.getHttpClient();
		try { 
			HttpGet request = new HttpGet(urls[0]);
			HttpParams params = new BasicHttpParams();
			HttpConnectionParams.setSoTimeout(params, 60000); // 1 minute
			request.setParams(params);
			HttpResponse response = httpClient.execute(request);
			byte[] image = EntityUtils.toByteArray(response.getEntity());
			Bitmap mBitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
			return mBitmap;
		} 
		catch (IOException e) {
		} 
		return null; 
	} 
} 
6
CodeRank
This code example shows how to use the following methods:setURI, getParams, setParams

Related Android HttpGet Questions & Answers:

Other Android HttpGet Examples

65:						url += "?" + paramString;
66:					}
67:					HttpGet httpGet = new HttpGet(url);
68:	
69:					httpResponse = httpClient.execute(httpGet);
-
65:						url += "?" + paramString;
66:					}
67:					HttpGet httpGet = new HttpGet(url);
68:	
69:					httpResponse = httpClient.execute(httpGet);

Read More

70:						url += "?" + paramString;
71:					}
72:					HttpGet httpGet = new HttpGet(url);
73:	
74:					httpResponse = httpClient.execute(httpGet);
-
70:						url += "?" + paramString;
71:					}
72:					HttpGet httpGet = new HttpGet(url);
73:	
74:					httpResponse = httpClient.execute(httpGet);

Read More

56:					String paramString = URLEncodedUtils.format(params, "utf-8");
57:					url += "?" + paramString;
58:					HttpGet httpGet = new HttpGet(url);
59:	
60:					HttpResponse httpResponse = httpClient.execute(httpGet);
-
56:					String paramString = URLEncodedUtils.format(params, "utf-8");
57:					url += "?" + paramString;
58:					HttpGet httpGet = new HttpGet(url);
59:	
60:					HttpResponse httpResponse = httpClient.execute(httpGet);

Read More

See Code Examples for Android HttpGet Methods: