在Activity中使用如下web请求
[java] view plaincopy
- 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方法中添加以下代码
[java] view plaincopy
- 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());
时间: 2024-10-10 16:29:19