参考 博客
如果 把网络请求放在 主线程中,android发送请求时会报错 android.os.NetworkOnMainThreadException
我的处理方法是, 单独用一个 类发送 网络请求,这个类 extends Thread,代码如下
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
//import org.json.JSONObject;
/**
* 网络访问
* Created by lyh on 2019/6/6.
*/
public class NetThread extends Thread{
private static final String url_prefix ="url地址";
private String url;
private JSONObject json;
private JSONObject json_get;
private Handler handler;
public NetThread(String url_suffix, Handler handler,JSONObject json){
this.url=url_prefix+url_suffix;
this.handler=handler;
this.json=json;
}
@Override
public void run(){
super.run();
json_get=post(json);
if(json_get!=null){
Log.e("json_get",json_get.toString());
}
dealResult();
}
public void dealResult(){
/*
返回结果
*/
Message message = new Message();
message.what=1;
if(json_get==null){
message.what=0;
}
message.obj = json_get;
handler.sendMessage(message);
}
....
}
在 Activity 中通过 handler处理 结果,代码如下
public void func(){
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
JSONObject jo=(JSONObject)msg.obj;
if (msg.what==1) {
try{
if((jo.getString("state")).equals("ok")){
// 处理成功的结果
}else{
// 处理失败的结果
}
}catch(Exception e){
// 处理失败的结果
}
}
}
};
/*
放数据
*/
JSONObject jo=new JSONObject();
jo.put("username",username);
jo.put("pwd",pwd);
// Log.e("json",jo.toString());
final NetThread netThread=new NetThread("register",handler,jo);
netThread.start();
}