android.os.NetworkOnMainThreadException

在搞android开发中过程中,是关于HttpURLConnection链接的,我是上传多个同一个名称的数据到服务器,本来在2.3版本上可以运行,但是在4.2版本上就报android.os.NetworkOnMainThreadException异常,无法将数据提交到服务器。

查了一些资料发现是一个APP如果在主线程中请求网络操作,将会抛出此异常。Android这个设计是为了防止网络请求时间过长而导致界面假死的情况发生。

解决方案有两个,一个是使用StrictMode,二是使用线程来操作网络请求。

第一种方法:简单暴力,强制使用,代码修改简单(但是非常不推荐)
在MainActivity文件的setContentView(R.layout.activity_main)下面加上如下代码


2
3
4
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 = ("\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);
}

android.os.NetworkOnMainThreadException,布布扣,bubuko.com

android.os.NetworkOnMainThreadException

上一篇:Cocos2d-3x:vs2012项目转为android项目需注意的地方


下一篇:BZOJ 4771 七彩树(可持久化线段树合并)