0

I'm trying to use a simple HTTP get to load a string from a webpage. However, when I run the app in the emulator, I get a strict policy violation, and nothing is displayed. The policy violation is listed as "policy=31 violation=4". If I add a permitNetwork() into the ThreadPolicy initialization, the LogCat tells me that google.com doesn't resolve to an address. Clearly, I'm missing something, but I was under the impression that this is how I should be handling network operations.

EDIT: I've altered my HttpExampleActivity.java, I now have this:

package com.android.httpexample;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy.Builder;
import android.widget.TextView;

public class HttpExampleActivity extends Activity {
    TextView httpStuff;

     @Override
        public void onCreate(Bundle savedInstanceState) {
         StrictMode.ThreadPolicy policy = new Builder().detectAll().penaltyLog().build(); 
         StrictMode.setThreadPolicy(policy);
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            new Thread(new Runnable() { 
                public void run() {

                    httpStuff = (TextView) findViewById(R.id.tvHttp);
                    httpStuff.post(new Runnable(){
                        public void run(){

                    GetProcedure test = new GetProcedure();
                    String returned;
                    try{
                        returned = test.getInternetData();
                        httpStuff.setText(returned);
                    } catch(Exception e){
                        e.printStackTrace();
                    }
                        }
                    });
                }
            }).start();


     }
}

In my GetProcedure.java, I have this:

package com.android.httpexample;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class GetProcedure {
    public String getInternetData() throws Exception {
        BufferedReader in = null;
        String data = null;
        try{
            HttpClient client = new DefaultHttpClient();
            URI website = new URI("http://google.com");
            HttpGet request = new HttpGet();
            request.setURI(website);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String l = "";
            String nl = System.getProperty("line.separator");
            while((l = in.readLine()) != null)
            {
                sb.append(l + nl);
            }
            in.close();
            data = sb.toString();
            return data;
        }finally{
            if(in != null){
                try{
                    in.close();
                    return data;
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}
Fibericon
  • 5,684
  • 12
  • 37
  • 64
  • Also, please bear in mind that `HttpUrlConnection`, not `HttpClient`, is the Google-preferred way of doing HTTP operations on Android, particularly for Android 2.3 and higher. See http://android-developers.blogspot.com/2011/09/androids-http-clients.html – CommonsWare Jun 17 '12 at 15:26

1 Answers1

3

You need to use a seperate Thread that executes the network activities. Android doesn't allow networking in the UI-thread since ICS and did raiss a force close after approx. 5 seconds before.

A good way to solve your task would be an AsyncTask that handles everying or a Thread with a listener for your Activity.

Check the Painless Threading Topic for more advice.

Tim
  • 6,692
  • 2
  • 25
  • 30
  • I've altered my HttpExampleActivity to use a new runnable, but that just provided a different error in my LogCat (W/NetworkManagementSocketTagger(93): setKernelCountSet(10045, 0) failed with errno -2). – Fibericon Jun 17 '12 at 16:12
  • Could you provide a full stack trace? I'd recommend not to just catch a generic Exception but the correct ones. – Tim Jun 17 '12 at 16:15
  • Is the stack trace separate from the LogCat? How would I enable logging of more specific exceptions? – Fibericon Jun 17 '12 at 16:34
  • logcat shows the stacktrace, too - but it contains more than just one line. – Tim Jun 17 '12 at 16:37
  • Seems like your accessing a file that doesn't exist on your emulator. How does it run on a real device? – Tim Jun 17 '12 at 21:36
  • I don't own a real device to test this on. All the java code in this app is in the question post, though - I'm not doing anything else. – Fibericon Jun 18 '12 at 07:42
  • I switched to AsyncTask and it worked just fine. No idea what the problem was with the other method, but since AsyncTask appears to be the preferred method anyway, I don't think it's important for me to find out. – Fibericon Jun 18 '12 at 12:02