Android Activity MainThread 中不能执行http通信解决办法

Android Activity MainThread 中不能执行http通信解决办法

今天在做离线文件传输时。用HTTP上传文件。程序一运行 报如下的错误
android.os.NetworkOnMainThreadException

原因是Google从3开始,强制默认禁止UI主线程发起通信请求 

解决办法:  

把通信的代码转移到子线程里去做, 比较靠谱的是new一个AyncTask,在里面做通信

                          有几个细节性的问题是,

                                第一, 一般原有通信的代码都是共通的API, 被许多个Activity调用, 一个良好的修改方法是在共通API里面new AyncTask

                               第二, 通信的API一般来说都是同步的, 你通信,然后画面主线程需要堵塞住,等待API的通信结果,再决定下面的业务逻辑的走向。

所以,这块可以采取 AyncTask.get(), 让主线程堵塞,直到通信结束。 当然,如果你需要将通信异步的话, 可以用Handler机制来解决


具体调用代码如下:HTTP异

步请求

package com.qqtech.ucstar.utils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;

public class HttpReqTask extends AsyncTask < Object, Object, HttpResponse > {

@Override
protected HttpResponse doInBackground(Object arg0) {
String fileUploadUrl
= (String) arg0[0];
String streamid
= (String) arg0[1];
File file
= (File) arg0[2];
//boolean paramBoolean = Boolean.parseBoolean((String) arg0[3]);
//String paramString3 = (String) arg0[4];
HttpClient localHttpClient = new DefaultHttpClient();
//String str1 = "fileName";
File localFile = file;
try {
if ((localFile == null) || (!localFile.exists()))
throw new IOException("文件不存在:" + localFile);
}
catch (IOException e1) {
e1.printStackTrace();
}

HttpPost localPostMethod
= new HttpPost(fileUploadUrl+"?streamid="+streamid+"&fileencode=UTF-8");
//MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null, Charset.forName("UTF-8"));
try {
FileBody bin
= new FileBody(file);
reqEntity.addPart(
"file", bin);
localPostMethod.setEntity(reqEntity);
HttpResponse response
= localHttpClient.execute(localPostMethod);
return response;
}
catch (Exception e) {
e.printStackTrace();
}

return null;
}


}



调用代码如下:


Object[] param = new Object[5];
     param[0] = answer.getUploadURL();
     param[1] = answer.getStreamid();
     param[2] = new File(answer.getFileURL());
     param[3] = "false";
     param[4] = "";
     AsyncTask res = new HttpReqTask().execute(param);
     HttpResponse rep = null;
     rep = (HttpResponse) res.get();
     if (rep.getStatusLine().getStatusCode() == 200) {
      System.out.println("文件上传成功");
     }else{
      System.out.println("文件上传失败");
     }
    }





你可能感兴趣的:(Android Activity MainThread 中不能执行http通信解决办法)