先前做過一個小 demo,用 node.js 回應 GET 與 POST 請求,當時的用戶端是瀏覽器。既然最近正在學 Android,那不如把兩者湊在一起:node.js 負責當伺服器端接收請求,Android 當用戶端發送請求,跑通一條完整的 HTTP 往返鏈路。
先建立 HTTP 伺服器,並依請求方法分流;POST 的內容需要透過 data 與 end 事件逐段收集:
var http = require('http');
var server = http.createServer();
var querystring = require('querystring');
var postResponse = function(req, res) {
var info = '';
req.addListener('data', function(chunk){
info += chunk;
})
.addListener('end', function(){
info = querystring.parse(info);
res.setHeader('content-type','text/html; charset=UTF-8');// 回應編碼
res.end('Hello World POST ' + info.name, 'utf8');
})
}
var getResponse = function (req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
var name = require('url').parse(req.url, true).query.name
res.end('Hello World GET ' + name, 'utf8');
}
var requestFunction = function (req, res){
req.setEncoding('utf8');// 請求編碼
if (req.method == 'POST'){
return postResponse(req, res);
}
return getResponse(req, res);
}
server.on('request', requestFunction);
server.listen(8080, "192.168.9.194");
console.log('Server running at https://192.168.9.194:8080/');
整體結構和先前差不多,最大的差別在綁定的位址與埠號。這一點非常關鍵:寫成 127.0.0.1 時只有本機連得上,而 Android 模擬器或真機對它而言是另一台機器,所以必須綁到實際的區域網路 IP,這裡用的是 192.168.9.194,埠號 8080。
畫面上放一個文字區塊與四顆按鈕,分別走 Java 原生 API 與 Apache HttpClient 的 GET/POST:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="java get"
android:onClick="javaGet" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="java post"
android:onClick="javaPost" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="apache get"
android:onClick="apacheGet" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="apache post"
android:onClick="apachePost" />
</LinearLayout>
</LinearLayout>
別忘了在 AndroidManifest.xml 中加上網路權限,否則請求會直接被系統擋下:
<uses-permission android:name="android.permission.INTERNET" />
package com.zhang.test08_01;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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 org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class Test08_01Activity extends Activity {
private TextView textView1;
// 不能用 localhost;localhost 指的是(模擬的)手機本身,
// 必須指定實際 Web 伺服器的 IP 位址或 DNS 名稱。
private static final String TEST_URL = "https://192.168.9.194:8080/";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView1 = (TextView)findViewById(R.id.textView1);
}
public void javaGet(View v) {
String str = "";
try {
str = URLEncoder.encode("抓哇", "UTF-8");
} catch (UnsupportedEncodingException e) {
}
URL url = null;
try {
url = new URL(TEST_URL + "?name=javaGet" + str);
} catch (MalformedURLException e) {
}
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
textView1.setText(e.getMessage());
return;
}
// method 的預設值就是 "GET"
getResponseJava(urlConnection);
}
public void javaPost(View v) {
URL url = null;
try {
url = new URL(TEST_URL);
} catch (MalformedURLException e) {
}
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
textView1.setText(e.getMessage());
return;
}
try {
urlConnection.setRequestMethod("POST");
} catch (ProtocolException e) {
}
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = null;
try {
out = new BufferedOutputStream(urlConnection.getOutputStream());// 請求
} catch (IOException e) {
urlConnection.disconnect();
textView1.setText(e.getMessage());
return;
}
String str = "";
try {
str = URLEncoder.encode("抓哇", "UTF-8");
} catch (UnsupportedEncodingException e) {
}
Writer writer = null;
try {
writer = new OutputStreamWriter(out, "UTF-8");
} catch (UnsupportedEncodingException e1) {
}
try {
writer.write("name=javaPost" + str);
} catch (IOException e) {
urlConnection.disconnect();
textView1.setText(e.getMessage());
return;
} finally {
try {
writer.flush();
writer.close();
} catch (IOException e) {
}
}
getResponseJava(urlConnection);
}
public void apacheGet(View v) {
HttpGet request = new HttpGet(TEST_URL + "?name=apacheGet阿帕奇");
getResponseApache(request);
}
public void apachePost(View v) {
HttpPost request = new HttpPost(TEST_URL);
List<NameValuePair> params = new ArrayList<NameValuePair>(1);
params.add(new BasicNameValuePair("name", "apachePost阿帕奇"));
HttpEntity formEntity = null;
try {
formEntity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
}
request.setEntity(formEntity);
getResponseApache(request);
}
private void getResponseJava(HttpURLConnection urlConnection) {
InputStream in = null;
try {
in = new BufferedInputStream(urlConnection.getInputStream());// 回應
} catch (IOException e) {
urlConnection.disconnect();
textView1.setText(e.getMessage());
return;
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
}
StringBuilder result = new StringBuilder();
String tmp = null;
try {
while ((tmp = reader.readLine()) != null) {
result.append(tmp);
}
} catch (IOException e) {
textView1.setText(e.getMessage());
return;
} finally {
try {
reader.close();
urlConnection.disconnect();
} catch (IOException e) {
}
}
textView1.setText(result);
}
private void getResponseApache(HttpUriRequest request) {
HttpClient client = new DefaultHttpClient();
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e) {
textView1.setText(e.getMessage());
} catch (IOException e) {
textView1.setText(e.getMessage());
}
if (response == null) {
return;
}
String result = null;
if (response.getStatusLine().getStatusCode() == 200) {
try {
result = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ParseException e) {
result = e.getMessage();
} catch (IOException e) {
result = e.getMessage();
}
} else {
result = "error response " + response.getStatusLine().toString();
}
textView1.setText(result);
}
}
三個細節值得留意。第一,中文參數一定要先用 URLEncoder.encode 編碼,伺服器端也要用 req.setEncoding('utf8') 與回應標頭的 charset 對齊,兩邊編碼不一致就會看到亂碼。第二,Android 用戶端不能寫 localhost,因為那指向模擬器或手機自身,必須換成伺服器實際的 IP。第三,Apache 版的 GET 直接把中文寫進 query string,能否正確顯示端看系統的預設編碼,正式環境仍建議一律做 URL 編碼。
另外要補充的是,在較新的 Android 版本中,主執行緒(UI thread)已被禁止直接進行網路連線,上述範例若要實際運行,需改用 AsyncTask、執行緒加 Handler,或 ExecutorService 把網路操作移到背景執行緒,再把結果回傳給 UI 更新。