Anroid之HttpClient异步请求数据

来源:互联网 发布:win 2008 如何打开端口 编辑:程序博客网 时间:2024/04/26 07:47

现在来结合使用一下HttpClient与Asynctask~


代码编写如下:

服务器代码我就不写出来了,就是一个用户名和密码~

1.写一个类HttpClientUtil,来实现HttpClient对象的创建并且返回HttpResponse对象

public class HttpClientUtil {private static HttpClient httpClient;static{//1.创建HttpClient对象httpClient=new DefaultHttpClient();}//2.执行该方法返回一个HttpResponsepublic static HttpResponse sendRequest(String url,List<NameValuePair>list){HttpResponse response=null;try {if(list==null){//Get方式HttpGet get=new HttpGet(url);response=httpClient.execute(get);}else{//Post方式HttpPost post=new HttpPost(url);//3.对于HttpPost对象而言,可调用setEntity(HttpEntity)方法设置请求参数。//4.使用HttpEntity下的UrlEncodedFormEntitiy对象传入一个放入BasicNameValuePair的集合中提交的数据。post.setEntity(new UrlEncodedFormEntity(list));response=httpClient.execute(post);}}catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return response;}}

get方式和post方式就是有点不一样~它们请求数据的时候get方式没有NameValuePair~

2.写一个监听接口ResponseListener,来实现监听服务器返回的数据

public interface ResponseListener {public void onResult(String msg);public void onError(String msg);}
3.写下MainActivity中的get方法提交和post方法提交

//get方式public void get(View view){String nameTe=name.getText().toString();String pwdTe=pwd.getText().toString();HttpClientTask task=new HttpClientTask(this);//要传进去的参数task.execute(BASIC+"?name="+nameTe+"&pwd="+pwdTe);}//post方式public void post(View view){String nameTe=name.getText().toString();String pwdTe=pwd.getText().toString();List<NameValuePair>list=new ArrayList<NameValuePair>();list.add(new BasicNameValuePair("name", nameTe));list.add(new BasicNameValuePair("pwd", pwdTe));HttpClientTask task=new HttpClientTask(list, this);task.execute(BASIC);}
public static final String BASIC="http://192.168.207.1:8090/ConnectionServlet/LoginServlet";



看图就知道,我又写了一个类HttpClientTask~

4.编写HttpClientTask,让其继承Asynctask~

/*  * Params:输入参数,如果不需要传递参数,则直接设为Void即可 --String * Progress:子线程执行的百分比 --Void * Result:返回的参数 --HttpResonse */  public class HttpClientTask extends AsyncTask<String, Void, HttpResponse>{private List<NameValuePair>list;private ResponseListener listener;//Get请求public HttpClientTask(ResponseListener listener) {super();// TODO Auto-generated constructor stubthis.listener=listener;}//Post请求public HttpClientTask(List<NameValuePair>list,ResponseListener listener) {super();// TODO Auto-generated constructor stubthis.list=list;this.listener=listener;}        //doInBackground有返回值,并且返回值是由result决定的,      //参数列表首先是一个可变长参数,是由Params决定的            //执行时机:在onPreExecute方法执行后马上执行,该方法运行在后线程中      //作用:主要负责执行那些很耗时的后台处理工作,可以调用publishProgress方法来更新实时的任务进度  @Overrideprotected HttpResponse doInBackground(String... params) {// TODO Auto-generated method stubHttpResponse response;//这里会返回一个response    response=HttpClientUtil.sendRequest(params[0], list);return response;}//参数是由result决定的      //作用:后台的计算结果将显示出来      //可以进行一些结束处理  @Overrideprotected void onPostExecute(HttpResponse result) {// TODO Auto-generated method stubString msg;try {//result是响应内容//用EntityUtils.toString(HttpEntity,"编码方式")//将其转成为字符串msg=EntityUtils.toString(result.getEntity(), "UTF-8");    if(listener!=null){    listener.onResult(msg);    }}catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();listener.onResult("出错了");    }super.onPostExecute(result);}}
代码写的很清楚,我就不一一解释了~

最后在onPostExecute方法后面调用了接口中的俩个方法~

这俩个方法在MainActivity中被重写了~

@Overridepublic void onResult(String msg) {// TODO Auto-generated method stubSystem.out.println(msg);}@Overridepublic void onError(String msg) {// TODO Auto-generated method stubSystem.out.println("出错了");}
说实话,服务器返回的数据就是成功或者失败~

如果那个监听器为空的话,就代表链接错误,后台会打印出“出错了”

否则会打印出“成功”或者“失败”~


MainActivity完整代码:

public class MainActivity extends Activity implements ResponseListener{private EditText name,pwd;public static final String BASIC="http://192.168.207.1:8090/ConnectionServlet/LoginServlet";//get方式public void get(View view){String nameTe=name.getText().toString();String pwdTe=pwd.getText().toString();HttpClientTask task=new HttpClientTask(this);//要传进去的参数task.execute(BASIC+"?name="+nameTe+"&pwd="+pwdTe);}//post方式public void post(View view){String nameTe=name.getText().toString();String pwdTe=pwd.getText().toString();List<NameValuePair>list=new ArrayList<NameValuePair>();list.add(new BasicNameValuePair("name", nameTe));list.add(new BasicNameValuePair("pwd", pwdTe));HttpClientTask task=new HttpClientTask(list, this);task.execute(BASIC);}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);name=(EditText) findViewById(R.id.name);pwd=(EditText) findViewById(R.id.pwd);}@Overridepublic void onResult(String msg) {// TODO Auto-generated method stubSystem.out.println(msg);}@Overridepublic void onError(String msg) {// TODO Auto-generated method stubSystem.out.println("出错了");}}

源码免费:下载



0 0
原创粉丝点击