在Activity中使用如下web请求
- Stringurl="http://maps.google.com/maps/api/directions/xml?origin=22.592700,113.969100"+
- "&destination=23.046604,113.397510&sensor=false&mode=walking";
- HttpGetget=newHttpGet(url);
- StringstrResult="";
- try{
- HttpParamshttpParameters=newBasicHttpParams();
- HttpConnectionParams.setConnectionTimeout(httpParameters,6000);
- HttpClienthttpClient=newDefaultHttpClient(httpParameters);
- HttpResponsehttpResponse=null;
- httpResponse=httpClient.execute(get);
- if(httpResponse.getStatusLine().getStatusCode()==200){
- strResult=EntityUtils.toString(httpResponse.getEntity());
- }
- }catch(Exceptione){
- e.printStackTrace();
- }
发现请求总是无法得到,在浏览器中尝试发现请求语句没有问题
DDMS报错为:android.os.NetworkOnMainThreadException
经查询发现原来Android3.0以上对网络请求做了更严格的限制,若要继续按照以前的方式继续使用网络请求,须做一些特别的声明。
解决办法:
在Activiey的OnCreate方法中添加以下代码
- StrictMode.setThreadPolicy(newStrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites()
- .detectNetwork()//or.detectAll()foralldetectableproblems
- .penaltyLog()
- .build());
- StrictMode.setVmPolicy(newStrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
本文介绍了解决Android 3.0及以上版本中遇到的NetworkOnMainThreadException错误的方法,并提供了一个具体的示例,展示了如何通过StrictMode策略来允许主线程进行网络操作。

被折叠的 条评论
为什么被折叠?



