這一章我們主要來介紹網路資料的傳遞與處理,相信很多讀者都希望做出來的應用能跟網路上的資料進行互動,如微博,論壇之類的,這裡我們就要學習網路傳輸與返回資料的處理,首先網路傳遞參數有POST跟GET兩種協議,做過網頁或是學習過的同學應該知道.網頁每個表單中都有一個<form action="XXX" method="post">參數,這裡method就是提交表單參數使用的協議,當然,協議不止這兩種,還有檔案上傳協議,這我們以後會講,今天我們首來就來熟悉Android中對於POST跟GET協議的應用,首先我們提供了一個HttpConnectionUtil.java的輔助類,這裡面對POST跟GET進行了封裝
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import java.util.ArrayList;import java.util.List;import java.util.Map;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.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.methods.HttpUriRequest;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import android.os.Handler;import android.util.Log;public class HttpConnectionUtil{public static enum HttpMethod{GET, POST}/** * 非同步串連 * * @param url * 網址 * @param method * Http方法,POST跟GET * @param callback * 回調方法,返回給頁面或其他的資料 */public void asyncConnect(final String url, final HttpMethod method,final HttpConnectionCallback callback){asyncConnect(url, null, method, callback);}/** * 同步方法 * * @param url * 網址 * @param method * Http方法,POST跟GET * @param callback * 回調方法,返回給頁面或其他的資料 */public void syncConnect(final String url, final HttpMethod method,final HttpConnectionCallback callback){syncConnect(url, null, method, callback);}/** * 非同步帶參數方法 * * @param url * 網址 * @param params * POST或GET要傳遞的參數 * @param method * 方法,POST或GET * @param callback * 回調方法 */public void asyncConnect(final String url,final Map<String, String> params, final HttpMethod method,final HttpConnectionCallback callback){Handler handler = new Handler();Runnable runnable = new Runnable(){public void run(){syncConnect(url, params, method, callback);}};handler.post(runnable);}/** * 同步帶參數方法 * * @param url * 網址 * @param params * POST或GET要傳遞的參數 * @param method * 方法,POST或GET * @param callback * 回調方法 */public void syncConnect(final String url, final Map<String, String> params,final HttpMethod method, final HttpConnectionCallback callback){String json = null;BufferedReader reader = null;try{HttpClient client = new DefaultHttpClient();HttpUriRequest request = getRequest(url, params, method);HttpResponse response = client.execute(request);if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));StringBuilder sb = new StringBuilder();for (String s = reader.readLine(); s != null; s = reader.readLine()){sb.append(s);}json = sb.toString();}} catch (ClientProtocolException e){Log.e("HttpConnectionUtil", e.getMessage(), e);} catch (IOException e){Log.e("HttpConnectionUtil", e.getMessage(), e);} finally{try{if (reader != null){reader.close();}} catch (IOException e){// ignore me}}callback.execute(json);}/** * POST跟GET傳遞參數不同,POST是隱式傳遞,GET是顯式傳遞 * * @param url * 網址 * @param params * 參數 * @param method * 方法 * @return */private HttpUriRequest getRequest(String url, Map<String, String> params,HttpMethod method){if (method.equals(HttpMethod.POST)){List<NameValuePair> listParams = new ArrayList<NameValuePair>();if (params != null){for (String name : params.keySet()){listParams.add(new BasicNameValuePair(name, params.get(name)));}}try{UrlEncodedFormEntity entity = new UrlEncodedFormEntity(listParams);HttpPost request = new HttpPost(url);request.setEntity(entity);return request;} catch (UnsupportedEncodingException e){// Should not come here, ignore me.throw new java.lang.RuntimeException(e.getMessage(), e);}} else{if (url.indexOf("?") < 0){url += "?";}if (params != null){for (String name : params.keySet()){try{url += "&" + name + "="+ URLEncoder.encode(params.get(name), "UTF-8");} catch (UnsupportedEncodingException e){e.printStackTrace();}}}HttpGet request = new HttpGet(url);return request;}}/** * 回調介面 * @author Administrator * */public interface HttpConnectionCallback{/** * Call back method will be execute after the http request return. * * @param response * the response of http request. The value will be null if * any error occur. */void execute(String response);}}
這個類也是我從網上看到的,使用起來相當方便,希望讀者能學會怎樣使用,其實像java學習,可以將一些有用的類或是方法定義個自己包,將它們放進去,下次要用的話只要在主程式中調用就行了,這也是物件導向重要的方法.
這裡面的方法,我就沒有一行一行定義說明了,裡面用的都是HttpClient的中方法
接下來,我們用這個類來進行Android的應用
main.xml(模板檔案)
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="match_parent"android:layout_height="match_parent"><EditText android:layout_width="match_parent"android:layout_height="wrap_content" android:id="@+id/http_edit"android:text="http://"><requestFocus></requestFocus></EditText><RelativeLayout android:layout_width="match_parent"android:layout_height="wrap_content" android:id="@+id/relativeLayout1"><Button android:text="取消" android:layout_width="wrap_content"android:id="@+id/http_cancal" android:layout_height="wrap_content"android:layout_alignParentTop="true" android:layout_alignParentRight="true"></Button><Button android:text="確定" android:layout_width="wrap_content"android:id="@+id/http_ok" android:layout_height="wrap_content"android:layout_alignParentTop="true" android:layout_toLeftOf="@+id/http_cancal"android:layout_marginRight="14dp"></Button></RelativeLayout><ScrollView android:layout_width="match_parent"android:layout_height="match_parent"><TextView android:id="@+id/http_text" android:text="TextView"android:textAppearance="?android:attr/textAppearanceSmall"android:layout_height="match_parent" android:layout_width="match_parent"></TextView></ScrollView></LinearLayout>
然後就是主Actitiv的java代碼了
import android.app.Activity;import android.os.Bundle;import android.text.Html;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import com.kang.http.HttpConnectionUtil;import com.kang.http.HttpConnectionUtil.HttpConnectionCallback;import com.kang.http.HttpConnectionUtil.HttpMethod;public class HttpClientDemo extends Activity{private Button ok_btn;private Button cancal_btn;private EditText edit_text;private TextView text;@Overrideprotected void onCreate(Bundle savedInstanceState){// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.http_client);//確定按鈕ok_btn = (Button) findViewById(R.id.http_ok);ok_btn.setOnClickListener(new ClickEvent());//取消按鈕cancal_btn = (Button) findViewById(R.id.http_cancal);cancal_btn.setOnClickListener(new ClickEvent());//文本編輯框edit_text = (EditText) findViewById(R.id.http_edit);//文字框text = (TextView) findViewById(R.id.http_text);}//自訂按鈕點擊方法public class ClickEvent implements OnClickListener{@Overridepublic void onClick(View v){switch (v.getId()){case R.id.http_ok://網址String url = edit_text.getText().toString().trim();if (!url.equals("http://") && !url.equals("")){//自訂類,封裝了GET/POST方法,而且同樣也封裝了同步跟非同步方法HttpConnectionUtil conn = new HttpConnectionUtil();conn.asyncConnect(url, HttpMethod.GET,new HttpConnectionCallback(){@Overridepublic void execute(String response){text.setText(Html.fromHtml(response));}});}break;case R.id.http_cancal:edit_text.setText("http://");break;}}}}
看裡面 ClickEvent類中onClick方法中我們就使用了自訂的HttpConnectionUtil類,別急著運行了,接下來還有一步,也是最重要的,就是許可權的增加,你要訪問網路,肯定需要訪問網路的許可權,在AndroidManifest.xml中加入<uses-permission android:name="android.permission.INTERNET"></uses-permission>這一句,至於加哪裡,那你可別問我了,百度或是google一下吧,呵呵,賣賣關子,現在就可以運行了,看圖是不是跟我的一樣
你一定會奇怪,怎麼會有其他一些代碼呢?呵呵,這裡我們取出的是它的原始碼.OK,這一章講完了,下一章我們就要來實現Mysql資料庫+PHP+Android的顯示了,相信這會是很多讀者感興趣的一章,謝謝