The android.os.NetworkOnMainThreadException exception
Android与Web Server交换数据 碰到异常The android.os.NetworkOnMainThreadException exception
原始代码
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myBtn = (Button) this.findViewById(R.id.myBtn);
myText = (TextView) this.findViewById(R.id.myText);
myBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://localhost:8080/data.jsp");
HttpResponse response;
try {
response = client.execute(request);
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder textView = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null) {
textView.append(line);
}
myText.setText(textView); //使用远程数据
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/myBtn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Click Me" />
<TextView
android:id="@+id/myText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello Rick!!!" />
</LinearLayout>
启动本地Tomcat,访问地址:http://localhost:8080/data.jsp
data.jsp
Hello Android!!!!
<%
System.out.println("Request from client!!!");
%>
期望:点击按钮“Click Me”,TextView由 “Hello Rick!!!”
—> “Hello Android!!!!”
,万万没想到,抛出了异常!!!
Google到解决方案http://www.lucazanini.eu/en/2012/android/the-android-os-networkonmainthreadexception-exception/
加权限,同时加了代码。
改动如下:
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
Activity.java
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
结果后台没有抛出异常,但是没有任何反应,这个纠结了很久。。。。
后来发现: http://localhost:8080/data.jsp,不能使用localhost和127.0.0.1
只能使用机器内网IP:192.168.1.106
,然后成功了。
解决地址:http://stackoverflow.com/questions/5495534/java-net-connectexception-localhost-127-0-0-18080-connection-refused
测试结果