上次做了一個demo,試驗如何用node.js響應get post請求,http請求使用的浏覽器。我現在正在學Android,所以決定寫一個兩者結合的demo。node.js做服務端接收get post請求,android做客戶端發送get post請求。
相關閱讀:
http://www.linuxidc.com/Linux/2012-02/53536.htm 與 http://www.linuxidc.com/Linux/2012-02/53537.htm
先上node.js的代碼(保存為example6.js):
[javascript]
- 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 http://192.168.9.194:8080/');
代碼基本和上次一樣,主要是綁定的地址和端口變了(這個很重要,後邊再講)
再上android源代碼:
layout main,xml如下
[html]
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://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需要添加如下內容:
[html]
- <uses-permission android:name="android.permission.INTERNET"/>
java源代碼如下:
[java]
- 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;
-
- // You can't use localhost; localhost is the (emulated) phone. You need
- //to specify the IP address or DNS name of the actual web server.
- private static final String TEST_URL = "http://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 The default value is "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);
- }
- }