Android 3.0 访问WebService 出现 android.os.NetworkOnMainThreadException异常
以前用2.2 访问WebService没有问题,到3.0上访问出现android.os.NetworkOnMainThreadException
找了资料经过实践,解决方法是在activity类中的onCreate方法中添加strict代码,如下:
- public void 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()
- .penaltyLog()
- .penaltyDeath()
- .build());
- ......
- }
似乎是3.0在网络上做了更加严格的限制
package org.sword.android;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.Button;
public class InternetActivity extends Activity {
private static final String SERVER_UTL = "http://www.webservicex.net/WeatherForecast.asmx/GetWeatherByZipCode";
private Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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());
getWeather();
}
private void getWeather(){
try {
final String SERVER_URL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather"; // 定义需要获取的内容来源地址
HttpPost request = new HttpPost(SERVER_URL); // 根据内容来源地址创建一个Http请求
List params = new ArrayList();
params.add(new BasicNameValuePair("theCityCode", "长沙")); // 添加必须的参数
params.add(new BasicNameValuePair("theUserID", "")); // 添加必须的参数
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); // 设置参数的编码
HttpResponse httpResponse = new DefaultHttpClient().execute(request); // 发送请求并获取反馈
// 解析返回的内容
if (httpResponse.getStatusLine().getStatusCode() != 404)
{
String result = EntityUtils.toString(httpResponse.getEntity());
System.out.println("result =" + result);
}
} catch (Exception e) {
e.printStackTrace();
}
}