0

I am trying to send a HTTP request to http://www.google.com/ and want to save all responses in my android application. I tried many approaches but every time I got errors or logcat error or my emulator stopped.

Can you please point out what is wrong with my code and give me some configuration hints? I want to be able to use both GET and POST.

 public void executeHttpGet() throws Exception {
     BufferedReader in = null;
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI("http://www.google.com/"));
            HttpResponse response = client.execute(request);
            in = new BufferedReader
            (new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            result.setText(sb.toString());

            in.close();
            String page = sb.toString();
            System.out.println(page);
            Debug.out(sb.toString());

            } finally {
            if (in != null) {
                try {
                    in.close();
                    } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }   

LOGCAT:

04-09 20:56:07.730: E/AndroidRuntime(9128): FATAL EXCEPTION: main
04-09 20:56:07.730: E/AndroidRuntime(9128): java.lang.RuntimeException: Unable to start activity ComponentInfo{mainpackage.rest_client/mainpackage.rest_client.GetResponse}: android.os.NetworkOnMainThreadException
04-09 20:56:07.730: E/AndroidRuntime(9128):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at android.os.Looper.loop(Looper.java:137)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at android.app.ActivityThread.main(ActivityThread.java:5041)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at java.lang.reflect.Method.invokeNative(Native Method)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at java.lang.reflect.Method.invoke(Method.java:511)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at dalvik.system.NativeStart.main(Native Method)
04-09 20:56:07.730: E/AndroidRuntime(9128): Caused by: android.os.NetworkOnMainThreadException
04-09 20:56:07.730: E/AndroidRuntime(9128):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at mainpackage.rest_client.GetResponse.QueryGooglePlus(GetResponse.java:75)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at mainpackage.rest_client.GetResponse.onCreate(GetResponse.java:61)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at android.app.Activity.performCreate(Activity.java:5104)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-09 20:56:07.730: E/AndroidRuntime(9128):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
04-09 20:56:07.730: E/AndroidRuntime(9128):     ... 11 more
04-09 20:56:08.330: D/dalvikvm(9128): GC_CONCURRENT freed 204K, 11% free 2889K/3216K, paused 6ms+44ms, total 417ms
04-09 20:56:11.640: I/Process(9128): Sending signal. PID: 9128 SIG: 9
Damon
  • 67,688
  • 20
  • 135
  • 185
aqeel
  • 11
  • 3

4 Answers4

2

I think the doc description rich enough to understand exception NetworkOnMainThreadException

The exception that is thrown when an application attempts to perform a networking operation on its main thread.

This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. See the document

try this link which let you know how to deal with network operation http://developer.android.com/training/articles/perf-anr.html

dharmendra
  • 7,835
  • 5
  • 38
  • 71
1

You have a NetworkOnMainThreadException. Do your networking in an AsyncTask.

RvdK
  • 19,580
  • 4
  • 64
  • 107
  • 1
    rather than answering it, please close the question as duplicate from any of the zillions questions about NetworkOnMainThreadException. – njzk2 Apr 10 '13 at 13:21
  • @njzk2 you seem to be in a fowl mood based on your last few comments, perhaps you should take a break for SO for a while if it is upsetting you that much. Why do you care if one person chooses to help another person? – FoamyGuy Apr 10 '13 at 13:23
  • @FoamyGuy : i think having thousands (literally) of identical questions about NetworkOnMainThreadException does not _help_ anyone. Not the person who asked the question, as each answer may have a little more or a little less details and explanation, and not the person who will be searching for this answer, as they will find tons of questions and not know which to follow. This kind of question should be closed instantly, because it really only is about reading the exception and googling it. (sorry if you find my comments to be fowl, whatever that means) – njzk2 Apr 10 '13 at 14:06
  • @njzk2 not your comments themselves, but rather it seems as though you were in a bad mood. Perhaps I misinterpreted your mood based on a few of your comments, but I feel that although the question should've been closed as a dupe there is no reason to be upset at someone for providing an answer, if that is what they wish to do. I do not find the multiples to be inherently bad, the level of detail in the answer shouldn't matter as long as it is not incorrect. And once it gets closed they will all point to the more detailed answer, so I think it makes it easier to find rather than harder. – FoamyGuy Apr 10 '13 at 14:42
  • yes, 'once it gets closed'. hence the comment to ask for closure. – njzk2 Apr 10 '13 at 15:23
0

Please check if you have access to the internet in the Simulator.

If you are not getting the access to internet, then try below solution, it worked for me :)

Issue in accessing internet through android applications.

Ashis Kumar
  • 6,494
  • 2
  • 21
  • 36
0

When u face trivial issues like these, it's always better for your learning to first look for exception description by googling, then zero in on the issue by looking through the explanation and links given like these. It pretty much decreases your development time exponentially. Just a honest suggestion, I'm no expert :)

And ya, AsyncTask should do the trick.