写了个类,封装了HttpClient,HttpPost,想实现以后Activity 重复使用doPost(),程序运行到 httpres = httpc.execute(httppost); 后就报错了,程序终止运行,求大神指点。
package common.libs;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class DoHttpClient {
public String doPost(HashMap hmap,String postUrl)
{
String result="";
String pdata="{";
Set hset = hmap.entrySet();
Iterator iter = hset.iterator();
while(iter.hasNext())
{
Map.Entry entry = (Map.Entry) iter.next();
pdata +="\""+entry.getKey().toString()+"\":\""+entry.getValue().toString()+"\",";
}
pdata = pdata.substring(0, pdata.length()-1)+"}";
HttpPost httppost = new HttpPost(postUrl);
HttpClient httpc = new DefaultHttpClient();
List <NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pdatajson", pdata));
String results = "";
try {
httppost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpResponse httpres;
try {
httpres = httpc.execute(httppost);
if(httpres.getStatusLine().getStatusCode()== HttpStatus.SC_OK)
{
results += EntityUtils.toString(httpres.getEntity());
}else{
results +="操作失败"+httpres.getStatusLine().getStatusCode();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return results;
}
}
-------------调用实例------------------
DebugPost a = new DebugPost();
a.start();
public class DebugPost extends Thread{
public void run(){
DoHttpClient dhc = new DoHttpClient();
HashMap hmap = new HashMap();
hmap.put("name", "zhangshan");
hmap.put("password", "123456");
String texts = dhc.doPost(hmap,"http://www.domain.com/mobileClient/loginHandle");
handler.post(new Runnable(){
public void run(){
Toast.makeText(getApplicationContext(), texts, Toast.LENGTH_LONG).show();
}
});
}
问题已解决。报错原因是不能在主线程里执行网络耗时操作。之前的doPost() 在handler.post(new Runnble(){});里面执行了 其实还是UI线程进行了操作,所以报错退出了