您好,登錄后才能下訂單哦!
本文實(shí)例講述了Android開(kāi)發(fā)之HttpClient異步請(qǐng)求數(shù)據(jù)的方法。分享給大家供大家參考,具體如下:
前面一篇Android開(kāi)發(fā)筆記之:AsyncTask的應(yīng)用較為詳細(xì)的講述了Asynctask的原理與應(yīng)用,這里來(lái)結(jié)合使用一下HttpClient與Asynctask~
代碼編寫如下:
服務(wù)器代碼我就不寫出來(lái)了,就是一個(gè)用戶名和密碼~
1.寫一個(gè)類HttpClientUtil,來(lái)實(shí)現(xiàn)HttpClient對(duì)象的創(chuàng)建并且返回HttpResponse對(duì)象
public class HttpClientUtil { private static HttpClient httpClient; static{ //1.創(chuàng)建HttpClient對(duì)象 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.對(duì)于HttpPost對(duì)象而言,可調(diào)用setEntity(HttpEntity)方法設(shè)置請(qǐng)求參數(shù)。 //4.使用HttpEntity下的UrlEncodedFormEntitiy對(duì)象傳入一個(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)不一樣~它們請(qǐng)求數(shù)據(jù)的時(shí)候get方式?jīng)]有NameValuePair~
2.寫一個(gè)監(jiān)聽(tīng)接口ResponseListener,來(lái)實(shí)現(xiàn)監(jiān)聽(tīng)服務(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請(qǐng)求 public HttpClientTask(ResponseListener listener) { super(); // TODO Auto-generated constructor stub this.listener=listener; } //Post請(qǐng)求 public HttpClientTask(List<NameValuePair>list,ResponseListener listener) { super(); // TODO Auto-generated constructor stub this.list=list; this.listener=listener; } //doInBackground有返回值,并且返回值是由result決定的, //參數(shù)列表首先是一個(gè)可變長(zhǎng)參數(shù),是由Params決定的 //執(zhí)行時(shí)機(jī):在onPreExecute方法執(zhí)行后馬上執(zhí)行,該方法運(yùn)行在后線程中 //作用:主要負(fù)責(zé)執(zhí)行那些很耗時(shí)的后臺(tái)處理工作,可以調(diào)用publishProgress方法來(lái)更新實(shí)時(shí)的任務(wù)進(jìn)度 @Override protected HttpResponse doInBackground(String... params) { // TODO Auto-generated method stub HttpResponse response; //這里會(huì)返回一個(gè)response response=HttpClientUtil.sendRequest(params[0], list); return response; } //參數(shù)是由result決定的 //作用:后臺(tái)的計(jì)算結(jié)果將顯示出來(lái) //可以進(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ò)了"); }
說(shuō)實(shí)話,服務(wù)器返回的數(shù)據(jù)就是成功或者失敗~
如果那個(gè)監(jiān)聽(tīng)器為空的話,就代表鏈接錯(cuò)誤,后臺(tái)會(huì)打印出“出錯(cuò)了”
否則會(huì)打印出“成功”或者“失敗”~
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開(kāi)發(fā)入門與進(jìn)階教程》、《Android視圖View技巧總結(jié)》、《Android編程之a(chǎn)ctivity操作技巧總結(jié)》、《Android文件操作技巧匯總》、《Android資源操作技巧匯總》及《Android控件用法總結(jié)》
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。