手把手教你解决android网络请求问题:android.os.NetworkOnMainThreadException

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.share_mblog_view);
    new Thread(runnable).start();
}

Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        Bundle data = msg.getData();
        String val = data.getString("value");
        Log.i("mylog","请求结果-->" + val);
    }
}

Runnable runnable = new Runnable(){
    @Override
    public void run() {
        //
        // TODO: http request.
        //
        Message msg = new Message();
        Bundle data = new Bundle();
        data.putString("value","请求结果");
        msg.setData(data);
        handler.sendMessage(msg);
    }
}

   最近在搞基于android虚拟机的通信项目,就是实现android虚拟机上的客户端和其所在电脑上的服务器进行通信。但是在所有的东西都写好后,发现android虚拟机端总是在代码:

HttpResponse response = new DefaultHttpClient().execute(request);

 

处包错,其错误为:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.andconweb/com.example.andconweb.MainActivity}: android.os.NetworkOnMainThreadException
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at android.os.Handler.dispatchMessage(Handler.java:99)
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at android.os.Looper.loop(Looper.java:137)
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at android.app.ActivityThread.main(ActivityThread.java:5041)
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at java.lang.reflect.Method.invokeNative(Native Method)
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at java.lang.reflect.Method.invoke(Method.java:511)
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at dalvik.system.NativeStart.main(Native Method)
10-02 09:13:37.500: E/AndroidRuntime(2657): Caused by: android.os.NetworkOnMainThreadException
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at libcore.io.IoBridge.connect(IoBridge.java:112)
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at java.net.Socket.connect(Socket.java:842)
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
10-02 09:13:37.500: E/AndroidRuntime(2657): 	at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
.......

 本来以为是代码出错或者是获取Http连接时传入的URL有问题,传入的URL如下:

http://10.0.2.2:8080/AndroidWeb/loadMessage

 但是,在android虚拟机中的浏览器上输入该网址后,却得到了想要的信息。有此推断出错的地方不是服务器端的代码。

调试了好久,才发现是因为Http请求写在了主线程里,在4.0之后在主线程里面执行Http请求都会报这个错,大概是怕Http请求时间太长造成程序假死的情况吧。

  解决方法有两种,下面我分别介绍:

第一种,是在主线程中直接忽略,强制执行。(不推荐这种方法,但是该方法修改起来简单)

在MainActivity文件的setContentView(R.layout.activity_main)下面加上如下代码

if (android.os.Build.VERSION.SDK_INT > 9) {
		    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		    StrictMode.setThreadPolicy(policy);
		}

 如果,有报错就在class头上加上

 

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")

 

在onCreate上面加上:

@SuppressLint("NewApi")

 

 

第二种,启动另一个线程执行网络连接任务,比如使用Thread、Runnable、Handler(推荐使用这种方法)

代码如下:

 

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.share_mblog_view);
    new Thread(runnable).start();
}

Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        Bundle data = msg.getData();
        String val = data.getString("value");
        Log.i("mylog","请求结果-->" + val);
    }
}

Runnable runnable = new Runnable(){
    @Override
    public void run() {
        //
        // TODO: http request.
        //
        Message msg = new Message();
        Bundle data = new Bundle();
        data.putString("value","请求结果");
        msg.setData(data);
        handler.sendMessage(msg);
    }
}

 

你可能感兴趣的:(android)