Executing a HTTP GET Request with HttpClient

2 votes · 5 comments

Retrieve the contents of a stream via a HTTP GET.

raw ·
copy
· download
public static InputStream getInputStreamFromUrl(String url) { InputStream content = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(new HttpGet(url)); content = response.getEntity().getContent(); } catch (Exception e) { Log.("[GET REQUEST]", "Network exception", e); } return content; }
Add a comment

5 Comments

Nice, but it should be:

Log.e("[GET REQUEST]", "Network exception");

instead of

Log.("[GET REQUEST]", "Network exception", e);

;)

Tom

Reply · Sept. 8, 2009, 8:03 p.m.

@Tom: Why? If you pass the Throwable (Exception) it'll log it.

Reply · Sept. 9, 2009, 1 p.m.

should this be in a thread or the HttpClient have it's own thread?

Reply · Sept. 12, 2009, 1:45 a.m.

Sidenote: You can read the InputStream into a String with this sippet: http://www.androidsnippets.com/get-the-content-from-a-httpresponse-or-any-inputstream-as-a-string

Reply · March 8, 2011, 11:07 p.m.

Hello, I tried to use this code but it seems to not work for me. Here is my code try { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response1 = httpclient.execute(new HttpGet("http://hyipicai.zxq.net/test.php")); if (response1 != null) { Toast.makeText(getApplicationContext(), "test Get Ok", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "no response for Get", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { Toast.makeText(getApplicationContext(), "Other exception", Toast.LENGTH_LONG).show(); tvError.setText(e.getMessage()); } I always go in the exception and there is no message in my TextView. I added the Internet permission in the manifest. It's not working on my AVD and on my phone. Do you have an idea of the problem ?

Thanks a lot Matthieu

Reply · Jan. 10, 2013, 9:13 a.m.