我无法打印来自HttpClient的状态(NetworkOnMainThreadException)

时间:2013-10-22 19:37:10

标签: java android

我只是想学习从网站获取数据。首先,我想获取状态代码并打印出来。

public class Json extends Activity{

    TextView tvStatus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.json);  
        tvStatus = (TextView) findViewById(R.id.tvStatus);
        try {
            String data = readLocalhost();
            tvStatus.setText(data);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public String readLocalhost() throws ClientProtocolException, IOException
    {
        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet("http://localhost");
        HttpResponse response = client.execute(get);
        StatusLine status = response.getStatusLine();
        String data = status.toString();    

        return data;

    }

我已经添加了互联网许可。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.channel"
    android:versionCode="1"
    android:versionName="1.0"
    android:name="android.permission.INTERNET"
     >

这是logcat。

10-22 15:30:42.292: I/Choreographer(1011): Skipped 33 frames!  The application may be doing too much work on its main thread.
10-22 15:30:43.032: D/AndroidRuntime(1011): Shutting down VM
10-22 15:30:43.032: W/dalvikvm(1011): threadid=1: thread exiting with uncaught exception (group=0x41465700)
10-22 15:30:43.182: D/dalvikvm(1011): GC_FOR_ALLOC freed 147K, 9% free 2867K/3132K, paused 53ms, total 58ms
10-22 15:30:43.182: E/AndroidRuntime(1011): FATAL EXCEPTION: main
10-22 15:30:43.182: E/AndroidRuntime(1011): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.channel/com.example.channel.Json}: android.os.NetworkOnMainThreadException
10-22 15:30:43.182: E/AndroidRuntime(1011):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at android.os.Looper.loop(Looper.java:137)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at android.app.ActivityThread.main(ActivityThread.java:5103)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at java.lang.reflect.Method.invokeNative(Native Method)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at java.lang.reflect.Method.invoke(Method.java:525)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at dalvik.system.NativeStart.main(Native Method)
10-22 15:30:43.182: E/AndroidRuntime(1011): Caused by: android.os.NetworkOnMainThreadException
10-22 15:30:43.182: E/AndroidRuntime(1011):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at com.example.channel.Json.readLocalhost(Json.java:43)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at com.example.channel.Json.onCreate(Json.java:27)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at android.app.Activity.performCreate(Activity.java:5133)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-22 15:30:43.182: E/AndroidRuntime(1011):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-22 15:30:43.182: E/AndroidRuntime(1011):     ... 11 more
10-22 15:32:24.912: I/Process(1011): Sending signal. PID: 1011 SIG: 9

如何解决这个问题?我说我是新手。请尽可能清楚地输入您的答案。 感谢。

1 个答案:

答案 0 :(得分:3)

Caused by: android.os.NetworkOnMainThreadException

这意味着您正在主线程上执行HTTP请求。自 Android Honeycomb 版本以来,这种方式已经不再适合了。您必须使用第二个线程(实际上是background thread)来实现您的HTTP请求。

为什么?

因为,如果您在主线程中运行网络方法,则UI将被阻止,并且在您的方法结束之前,用户无法执行任何操作。

如何:

使用extends AsyncTask<String, String, String>的AsyncTask类并在DoInBackground方法中执行您的操作。在OnpostExcute上,您可以处理回复。

请参阅Android Developers Post

这是您的问题的回复:

class Async extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(MyActivity.this);
        progressDialog.setTitle("Merci de patienter");
        progressDialog.setMessage("Chargement en cours");
        progressDialog.setCancelable(false);
        progressDialog.setIndeterminate(true);
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... aurl) {

        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet("http://localhost");
            HttpResponse response = client.execute(get);
            StatusLine status = response.getStatusLine();
            String data = status.toString();    

            return data;
        } catch (Exception e) {}
        return null;

    }

    @Override
    protected void onPostExecute(String result) {
        if (progressDialog!=null) {
            progressDialog.dismiss();
        }
         tvStatus.setText(result);

    }
}

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.json);  
            tvStatus = (TextView) findViewById(R.id.tvStatus);
            new Async().execute();
    }