android.os.NetworkOnMainThreadException

【android.os.NetworkOnMainThreadException】追风赶月莫停留,平芜尽处是春山。这篇文章主要讲述android.os.NetworkOnMainThreadException相关的知识,希望能为你提供帮助。
在搞android开发中过程中。是关于HttpURLConnection链接的,我是上传多个同一个名称的数据到server,本来在2.3版本号上能够执行。可是在4.2版本号上就报android.os.NetworkOnMainThreadException异常。无法将数据提交到server。
查了一些资料发现是一个APP假设在主线程中请求网络操作,将会抛出此异常。Android这个设计是为了防止网络请求时间过长而导致界面假死的情况发生。
解决方式有两个,一个是使用StrictMode,二是使用线程来操作网络请求。

第一种方法:简单暴力,强制使用,代码改动简单(可是很不推荐)
在MainActivity文件的setContentView(R.layout.activity_main)以下加上例如以下代码


234
if (android.os.Build.VERSION.SDK_INT > 9) {        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();         StrictMode.setThreadPolicy(policy); }
另外一种方法就是我使用的方法也是我要推荐的方法,将请求网络资源的代码使用异步任务类去处理的,不用堵塞UI线程。


/**
* 表单上传多值 和多图片
* @param url 链接地址
* @param handler 回调handler
* @param valus 值
* @param sameValuNames 存放须要上传的名字同样的value
* @param sameValueName 同样的名字的上传名称
* @param imageUrl 图片路径(上传名称不同)
* @param sameImageUrlName 存放上传多个图片(上传名称同样)
* @param sameImageName 存放上传多个图片要求上传名称同样
*/
public static void myPostHttpConnection(String myUrl,final Handler handler,final Map< String, String> valus,final Map< String, String> sameValuNames,final String sameValueName,final Map< String, String> imageUrl,final Map< String, String> sameImageUrlName,final String sameImageName){
Log.d(" TAG" , " myUrl" + myUrl);
//Log.d(" TAG" , " sameImageUrlName.size()" + sameImageUrlName.size());
//Log.d(" TAG" , " sameImageName" + sameImageName);
//Log.d(" TAG" , " sameValueName" + sameValueName);
//Log.d(" TAG" , " sameValuNames" + sameValuNames.size());
new AsyncTask< String,Void,String> () {
@Override
protected String doInBackground(String... params) {
try {
// 定义数据分隔线
String BOUNDARY = " ------------------------7dc2fd5c0894" ;
// 定义最后数据分隔线
byte[] end_data = https://www.songbingjia.com/android/(" /r/n--" + BOUNDARY + " --/r/n" ).getBytes();
//Log.d(" TAG" , " params[0]" + params[0]);
URL url = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod(" POST" );
conn.setRequestProperty(" connection" , " Keep-Alive" );
conn.setRequestProperty(" user-agent" ,
" Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)" );
conn.setRequestProperty(" Charsert" , " UTF-8" );
conn.setRequestProperty(" Content-Type" ,
" multipart/form-data; boundary=" + BOUNDARY);
StringBuffer myparams=null;
OutputStream out=null;
out = new DataOutputStream(conn.getOutputStream());
myparams = new StringBuffer();
//不同名称的的參数
if(valus!=null){
//Log.d(" TAG" , " 有bu同样參数的提交" );
Iterator iter = valus.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String val = entry.getValue().toString();
String key = entry.getKey().toString();
// Log.d(" TAG" , " bu同样參数" + val+ " ===" + key);
myparams.append(" --" + BOUNDARY + " \r\n" );
myparams.append(" Content-Disposition: form-data; name=\" " + key+ " \" \r\n\r\n" );
myparams.append(val);
myparams.append(" \r\n" );
}
}
out.write(myparams.toString().getBytes());
//同样的參数
if(sameValueName!=null){
//Log.d(" TAG" , " 有同样參数的提交" + sameValueName);
Iterator iter2 = sameValuNames.entrySet().iterator();
while (iter2.hasNext()) {
Map.Entry entry = (Map.Entry) iter2.next();
String val = entry.getValue().toString();
//Log.d(" TAG" , " 同样參数" + val);
//String key = entry.getKey().toString();
myparams.append(" --" + BOUNDARY + " \r\n" );
myparams.append(" Content-Disposition: form-data; name=\" " + sameValueName+ " \" \r\n\r\n" );
myparams.append(val);
myparams.append(" \r\n" );
}
}
out.write(myparams.toString().getBytes());

//上传上传名称不同的图片
if(imageUrl!=null){
Iterator iter3 = imageUrl.entrySet().iterator();
while (iter3.hasNext()) {
Map.Entry entry = (Map.Entry) iter3.next();
Object val = entry.getValue();
String key = entry.getValue().toString();
File file = new File(val.toString());
StringBuilder sb = new StringBuilder();
sb.append(" --" );
sb.append(BOUNDARY);
sb.append(" \r\n" );
sb.append(" Content-Disposition: form-data; name=\" " + key+ " \" ; filename=\" " + file.getName() + " \" \r\n" );
// 这里不能漏掉,依据文件类型来来做处理。因为上传的是图片,所以这里能够写成image/pjpeg
sb.append(" Content-Type:image/pjpeg\r\n\r\n" );
out.write(sb.toString().getBytes());
DataInputStream in = new DataInputStream(new FileInputStream(
file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
out.write(" \r\n" .getBytes());
in.close();  
}
}
//上传上传名称同样的图片
Log.d(" TAG" , " 上传上传名称同样的图片" );
if(sameImageName!=null){
Log.d(" TAG" , " 上传上传名称同样的图片" + sameImageName);
Iterator iter4 = sameImageUrlName.entrySet().iterator();
while (iter4.hasNext()) {
Map.Entry entry = (Map.Entry) iter4.next();
Object val = entry.getValue();
Log.d(" TAG" , " 上传上传名称同样的图片" + val);
//String key = entry.getValue().toString();
File file = new File(val.toString());
StringBuilder sb = new StringBuilder();
sb.append(" --" );
sb.append(BOUNDARY);
sb.append(" \r\n" );
sb.append(" Content-Disposition: form-data; name=\" " + sameImageName+ " \" ; filename=\" " + file.getName() + " \" \r\n" );
// 这里不能漏掉,依据文件类型来来做处理,因为上传的是图片。所以这里能够写成image/pjpeg
sb.append(" Content-Type:image/pjpeg\r\n\r\n" );
out.write(sb.toString().getBytes());
DataInputStream in = new DataInputStream(new FileInputStream(
file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
out.write(" \r\n" .getBytes());
in.close();  
}

}
Log.d(" TAG" , " 上传完毕数据" );
out.write(end_data);
out.flush();
out.close();
// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
Log.d(" TAG" , " 返回数据" + reader);
String line = null;
while ((line = reader.readLine()) != null) {
Log.d(" TAG" , " 返回数据。
" + line);
Message msg=new Message();
msg.what=200;
msg.obj=line;
handler.sendMessage(msg);
MyProgressDialog.dismiss();
}

} catch (Exception e) {
Log.d(" TAG" , " 发送POST请求出现异常。" + e);
Message msg=new Message();
msg.what=0;
//msg.obj=" 无网络连接" ;
msg.obj=" 异常" + e;
handler.sendMessage(msg);
MyProgressDialog.dismiss();
}
 

return null;
}
@Override
protected void onPostExecute(String result) {
Log.d(" TAG" , " success" );
}
}.execute(myUrl);
}


















































































































































































    推荐阅读