写了一个发送POST请求的程序,能够在Android 2.3的虚拟机上运行,但是我把程序放到Galaxy Nexus(Android 4.2.1)上运行,直接抛出android.os.NetworkOnMainThreadException,我郁闷了很久,后来在官方文档里找到了说明,在Android 4.x之后,不允许在主线程进行网络访问的操作。解决办法只有两种。
第一种是在主线程增加如下代码:
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() // or .detectAll() for all detectable problems .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .penaltyLog() .penaltyDeath() .build());
第二种就是另外开一个线程:
Runnable access = new Runnable() { public void run() { // TODO Auto-generated method stub try { //发出HttpRequest httpPost.setEntity(new UrlEncodedFormEntity(list,HTTP.UTF_8)); //取得HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost); //若返回值为200,那么取回字符串 if(httpResponse.getStatusLine().getStatusCode() == 200) { reString = EntityUtils.toString(httpResponse.getEntity()); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } }
在主线程使用:
new Thread(access).start();
这样就能避免抛出异常