解决NetworkOnMainThreadException

简介: 今天在Android 访问 WebService 的时候遇到,错误Caused by: android.os.NetworkOnMainThreadException,查了下原因上在4.0之后在主线程里面执行Http请求都会报这个错,大概是怕Http请求时间太长造成程序假死的情况吧,于是就用另外一个线程处理请求,用的是handler机制,源码如下:package com.
今天在Android 访问 WebService 的时候遇到,错误Caused by: android.os.NetworkOnMainThreadException,查了下原因上在4.0之后在主线程里面执行Http请求都会报这个错,大概是怕Http请求时间太长造成程序假死的情况吧,于是就用另外一个线程处理请求,用的是handler机制,源码如下:

package
com.example.webservicetest; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpResponseException; import org.ksoap2.transport.HttpTransportSE; import org.xmlpull.v1.XmlPullParserException; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.StrictMode; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; @SuppressLint("NewApi") @TargetApi(Build.VERSION_CODES.GINGERBREAD) public class MainActivity extends Activity { EditText editPara; EditText editRes; Button btnCal; Handler handler = null; /* * @TargetApi(Build.VERSION_CODES.GINGERBREAD) * * @SuppressLint("NewApi") * * @Override */ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /* * if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy * policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); * StrictMode.setThreadPolicy(policy); } */ handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); Bundle data = msg.getData(); String val = data.getString("value"); Toast.makeText(getApplicationContext(), "获取成功", Toast.LENGTH_LONG); editRes.setText(val); Log.i("mylog", "请求结果-->" + val); } }; InitView(); InitEvents(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } private void InitView() { editPara = (EditText) findViewById(R.id.editCity); editRes = (EditText) findViewById(R.id.editRes); btnCal = (Button) findViewById(R.id.btnCal); } private void InitEvents() { btnCal.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { // TODO Auto-generated method stub Runnable runnable = new Runnable() { @Override public void run() { // // TODO: http request. String sCity = editPara.getText().toString(); SoapObject sResult = TestWs(sCity); try { if (sResult == null) { Message msg = new Message(); Bundle data = new Bundle(); data.putString("value", "计算错误"); msg.setData(data); handler.sendMessage(msg); } else { String sText = parseWeather(sResult); Message msg = new Message(); Bundle data = new Bundle(); data.putString("value", sText); msg.setData(data); handler.sendMessage(msg); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } // } }; new Thread(runnable).start(); /* * String sCity = editPara.getText().toString(); * * SoapObject sResult = TestWs(sCity); * * String sText; try { sText = parseWeather(sResult); if * (sResult != null) { Toast.makeText(getApplicationContext(), * "获取成功", Toast.LENGTH_LONG); editRes.setText(sText); } } catch * (UnsupportedEncodingException e) { // TODO Auto-generated * catch block e.printStackTrace(); } */ } }); } private SoapObject TestWs(String sCity) { String NAMESPACE = "http://WebXml.com.cn/"; String URL = "http://www.webxml.com.cn/webservices/weatherwebservice.asmx"; String METHODNAME = "getWeatherbyCityName"; String SOAP_ACTION = "http://WebXml.com.cn/getWeatherbyCityName"; SoapObject so = new SoapObject(NAMESPACE, METHODNAME); HttpTransportSE httpSE = new HttpTransportSE(URL); httpSE.debug = true; SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); soapEnvelope.dotNet = true; soapEnvelope.bodyOut = so; so.addProperty("theCityName", sCity); soapEnvelope.setOutputSoapObject(so); try { httpSE.call(null, soapEnvelope); SoapObject seOut = (SoapObject) soapEnvelope.getResponse(); return seOut; /* * if(seOut!=null) { String sResult= (String) * seOut.getProperty("getWeatherbyCityNameResult"); * * return sResult; * * } */ } catch (HttpResponseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } private String parseWeather(SoapObject detail) throws UnsupportedEncodingException { String date = detail.getProperty(6).toString(); String weatherToday = "今天:" + date.split("")[0]; weatherToday = weatherToday + "\n天气:" + date.split("")[1]; weatherToday = weatherToday + "\n气温:" + detail.getProperty(5).toString(); weatherToday = weatherToday + "\n风力:" + detail.getProperty(7).toString() + "\n"; System.out.println("weatherToday is " + weatherToday); return weatherToday; } }

 

相关文章
|
Ubuntu Linux iOS开发
Ubuntu下的几种常见输入法极其配置方式
Ubuntu下的几种常见输入法极其配置方式
1377 0
|
前端开发
前端学习笔记202303学习笔记第四天-Vue3.0-安装和使用vue-devtools
前端学习笔记202303学习笔记第四天-Vue3.0-安装和使用vue-devtools
286 0
|
3天前
|
云安全 安全 网络安全
|
3天前
|
JavaScript 安全 前端开发
Nodejs Brotli decoder 代码执行漏洞 (CVE-2026-111497)10629
Node.js发布安全更新修复Brotli解码器高危RCE漏洞(CVE-2026-111497),建议受影响版本用户立即升级。
1730 1
|
9天前
|
人工智能 API 开发工具
DeepSeek Harness 神插件:白嫖 13 家大厂模型
`dsh-our-free-model` 是 DeepSeek Harness 神级插件:零配置、零API Key、零账号,聚合13家大厂免费模型(含DeepSeek V4.1 Flash、Kimi K3等),支持本地网关、用量看板与自动降级,真正实现“白嫖即用”。
1509 33
|
3天前
|
安全 应用服务中间件 Go
PHP2Shell 漏洞拆解:WordPress 与 nginx 为何中招
PHP2Shell 双 RCE 已遭在野利用:WordPress、Drupal 全在射程内,nginx 其实另有洞。拆成因与修复顺序
PHP2Shell 漏洞拆解:WordPress 与 nginx 为何中招
|
10天前
|
安全 Linux 芯片
【万字长文】Ollama下载、安装、配置、使用保姆级教程(2026最新图解)
Ollama 是一款免费开源的本地大模型运行工具,支持 DeepSeek、Qwen 等主流模型,一条命令即可下载运行。2026 最新版 v0.35.1 官方安装包(1.47GB)已提供国内直连下载,纯本地、离线可用、无广告、无隐私泄露风险。
982 2
|
14天前
|
存储 人工智能 安全
千问办公官网入口网页版登录:qwenwork.cn 注册送2000积分、登录送100积分
阿里云千问办公(QwenWork)是AI智能工作平台,支持一句话生成PPT、表格、网页、视频及数据分析。个人免费版送2000积分+每日登录赠100分,含1GB存储、5个发布页;企业版198元/席/月起。阿里千问办公QwenWork官网:https://t.aliyun.com/U/0VCTGt 阿里AI工作平台,一句话完成数据分析、PPT 生成、视频剪辑、网页搭建等复杂任务