Android 4.0.3 在Activity中使用Web请求出现 android.os.NetworkOnMainThreadException异常

问题:

在Activity中使用如下web请求

String url = "http://maps.google.com/maps/api/directions/xml?origin=22.592700,113.969100" +   
    "&destination=23.046604,113.397510&sensor=false&mode=walking";   
     
  HttpGet get = new HttpGet(url);   
  String strResult = "";   
  try {   
   HttpParams httpParameters = new BasicHttpParams();   
   HttpConnectionParams.setConnectionTimeout(httpParameters, 6000);   
   HttpClient httpClient = new DefaultHttpClient(httpParameters);    
      
   HttpResponse httpResponse = null;   
   httpResponse = httpClient.execute(get);   
      
   if (httpResponse.getStatusLine().getStatusCode() == 200){   
    strResult = EntityUtils.toString(httpResponse.getEntity());   
   }   
  } catch (Exception e) {   
   e.printStackTrace(); 
  }  

发现请求总是无法得到,在浏览器中尝试发现请求语句没有问题

DDMS报错为:android.os.NetworkOnMainThreadException

经查询发现原来Android3.0以上对网络请求做了更严格的限制,若要继续按照以前的方式继续使用网络请求,须做一些特别的声明。

 

解决办法:

在Activiey的OnCreate方法中添加以下代码

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());

 

添加之后问题得以解决,网络访问请求得以实现。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值