這一章我們主要來介紹網絡數據的傳遞與處理,相信很多讀者都希望做出來的應用能跟網絡上的數據進行互動,如微博,論壇之類的,這裡我們就要學習網絡傳輸與返回數據的處理,首先網絡傳遞參數有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;
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.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
{
@Override
public 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()
{
@Override
public 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的顯示瞭,相信這會是很多讀者感興趣的一章,謝謝
摘自:kangkangz4的專欄