欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android開發(fā)之HttpClient異步請求數(shù)據(jù)的方法詳解【附demo源碼下載】

 更新時(shí)間:2017年11月28日 12:12:03   作者:飄走的我  
這篇文章主要介紹了Android開發(fā)之HttpClient異步請求數(shù)據(jù)的方法,結(jié)合實(shí)例形式較為詳細(xì)的分析了Android HttpClient異步請求數(shù)據(jù)的相關(guān)操作技巧,并附帶完整demo源碼供讀者下載參考,需要的朋友可以參考下

本文實(shí)例講述了Android開發(fā)之HttpClient異步請求數(shù)據(jù)的方法。分享給大家供大家參考,具體如下:

前面一篇Android開發(fā)筆記之:AsyncTask的應(yīng)用較為詳細(xì)的講述了Asynctask的原理與應(yīng)用,這里來結(jié)合使用一下HttpClient與Asynctask~

代碼編寫如下:

服務(wù)器代碼我就不寫出來了,就是一個(gè)用戶名和密碼~

1.寫一個(gè)類HttpClientUtil,來實(shí)現(xiàn)HttpClient對象的創(chuàng)建并且返回HttpResponse對象

public class HttpClientUtil {
  private static HttpClient httpClient;
  static{
    //1.創(chuàng)建HttpClient對象
    httpClient=new DefaultHttpClient();
  }
  //2.執(zhí)行該方法返回一個(gè)HttpResponse
  public 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對象而言,可調(diào)用setEntity(HttpEntity)方法設(shè)置請求參數(shù)。
      //4.使用HttpEntity下的UrlEncodedFormEntitiy對象傳入一個(gè)放入BasicNameValuePair的集合中提交的數(shù)據(jù)。
      post.setEntity(new UrlEncodedFormEntity(list));
      response=httpClient.execute(post);
    }
    }catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return response;
  }
}

get方式和post方式就是有點(diǎn)不一樣~它們請求數(shù)據(jù)的時(shí)候get方式?jīng)]有NameValuePair~

2.寫一個(gè)監(jiān)聽接口ResponseListener,來實(shí)現(xiàn)監(jiān)聽服務(wù)器返回的數(shù)據(jù)

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);
  //要傳進(jìn)去的參數(shù)
  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";

看圖就知道,我又寫了一個(gè)類HttpClientTask~

4.編寫HttpClientTask,讓其繼承Asynctask~

/*
 * Params:輸入?yún)?shù),如果不需要傳遞參數(shù),則直接設(shè)為Void即可 --String
 * Progress:子線程執(zhí)行的百分比 --Void
 * Result:返回的參數(shù) --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 stub
    this.listener=listener;
  }
  //Post請求
  public HttpClientTask(List<NameValuePair>list,ResponseListener listener) {
    super();
    // TODO Auto-generated constructor stub
    this.list=list;
    this.listener=listener;
  }
  //doInBackground有返回值,并且返回值是由result決定的,
  //參數(shù)列表首先是一個(gè)可變長參數(shù),是由Params決定的
  //執(zhí)行時(shí)機(jī):在onPreExecute方法執(zhí)行后馬上執(zhí)行,該方法運(yùn)行在后線程中
  //作用:主要負(fù)責(zé)執(zhí)行那些很耗時(shí)的后臺處理工作,可以調(diào)用publishProgress方法來更新實(shí)時(shí)的任務(wù)進(jìn)度
  @Override
  protected HttpResponse doInBackground(String... params) {
    // TODO Auto-generated method stub
    HttpResponse response;
    //這里會返回一個(gè)response
    response=HttpClientUtil.sendRequest(params[0], list);
    return response;
  }
  //參數(shù)是由result決定的
  //作用:后臺的計(jì)算結(jié)果將顯示出來
  //可以進(jìn)行一些結(jié)束處理
  @Override
  protected void onPostExecute(HttpResponse result) {
    // TODO Auto-generated method stub
    String msg;
    try {
      //result是響應(yīng)內(nèi)容
      //用EntityUtils.toString(HttpEntity,"編碼方式")
      //將其轉(zhuǎn)成為字符串
      msg=EntityUtils.toString(result.getEntity(), "UTF-8");
      if(listener!=null){
        listener.onResult(msg);
      }
    }catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      listener.onResult("出錯(cuò)了");
    }
    super.onPostExecute(result);
  }
}

代碼寫的很清楚,我就不一一解釋了~

最后在onPostExecute方法后面調(diào)用了接口中的倆個(gè)方法~

這倆個(gè)方法在MainActivity中被重寫了~

@Override
  public void onResult(String msg) {
    // TODO Auto-generated method stub
    System.out.println(msg);
  }
  @Override
  public void onError(String msg) {
    // TODO Auto-generated method stub
    System.out.println("出錯(cuò)了");
  }

說實(shí)話,服務(wù)器返回的數(shù)據(jù)就是成功或者失敗~
如果那個(gè)監(jiān)聽器為空的話,就代表鏈接錯(cuò)誤,后臺會打印出“出錯(cuò)了”
否則會打印出“成功”或者“失敗”~

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);
    //要傳進(jìn)去的參數(shù)
    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);
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    name=(EditText) findViewById(R.id.name);
    pwd=(EditText) findViewById(R.id.pwd);
  }
  @Override
  public void onResult(String msg) {
    // TODO Auto-generated method stub
    System.out.println(msg);
  }
  @Override
  public void onError(String msg) {
    // TODO Auto-generated method stub
    System.out.println("出錯(cuò)了");
  }
}

附:完整實(shí)例代碼點(diǎn)擊此處本站下載。

更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android開發(fā)入門與進(jìn)階教程》、《Android視圖View技巧總結(jié)》、《Android編程之a(chǎn)ctivity操作技巧總結(jié)》、《Android文件操作技巧匯總》、《Android資源操作技巧匯總》及《Android控件用法總結(jié)

希望本文所述對大家Android程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評論