android + nodejs

 超哥  android  2014-10-08  2856  发表评论

本文参照了 http://www.blogjava.net/jelver/articles/143082.htmlhttp://www.blogjava.net/athrunwang/archive/2011/09/28/359680.html,《android SDK开发范例大全(第2版)》

上次做了一个demo,试验如何用node.js响应get post请求,http请求使用的浏览器。我现在正在学android,所以决定写一个两者结合的demo。node.js做服务端接收get post请求,android做客户端发送get post请求。

先上node.js的代码(保存为example6.js):

  1. var http = require('http');  
  2. var server = http.createServer();  
  3. var querystring = require('querystring');  
  4.   
  5.   
  6. var postResponse = function(req, res) {  
  7.     var info ='';  
  8.     req.addListener('data'function(chunk){  
  9.         info += chunk;  
  10.      })  
  11.     .addListener('end'function(){  
  12.         info = querystring.parse(info);  
  13.         res.setHeader('content-type','text/html; charset=UTF-8');//响应编码  
  14.         res.end('Hello World POST ' + info.name,'utf8');  
  15.      })  
  16. }  
  17.   
  18. var getResponse = function (req, res){  
  19.   res.writeHead(200, {'Content-Type''text/plain'});  
  20.   var name = require('url').parse(req.url,true).query.name  
  21.   res.end('Hello World GET ' + name,'utf8');  
  22. }  
  23.   
  24. var requestFunction = function (req, res){  
  25.     req.setEncoding('utf8');//请求编码  
  26.   
  27.     if (req.method == 'POST'){  
  28.         return postResponse(req, res);  
  29.     }  
  30.   
  31.     return getResponse(req, res);  
  32. }  
  33.   
  34. server.on('request',requestFunction);  
  35. server.listen(8080, "192.168.9.194");  
  36.   
  37. console.log('Server running at http://192.168.9.194:8080/');  

代码基本和上次一样,主要是绑定的地址和端口变了(这个很重要,后边再讲)

再上android源代码:

layout main,xml如下

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:id="@+id/textView1"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"/>  
  11.       
  12.     <LinearLayout  
  13.         android:layout_width="match_parent"  
  14.         android:layout_height="wrap_content" >  
  15.   
  16.         <Button  
  17.             android:layout_width="wrap_content"  
  18.             android:layout_height="wrap_content"  
  19.             android:text="java get"   
  20.             android:onClick="javaGet"/>  
  21.   
  22.         <Button  
  23.             android:layout_width="wrap_content"  
  24.             android:layout_height="wrap_content"  
  25.             android:text="java post"   
  26.             android:onClick="javaPost"/>  
  27.     </LinearLayout>   
  28.       
  29.     <LinearLayout  
  30.         android:layout_width="match_parent"  
  31.         android:layout_height="wrap_content" >  
  32.   
  33.         <Button  
  34.             android:layout_width="wrap_content"  
  35.             android:layout_height="wrap_content"  
  36.             android:text="apache get"   
  37.             android:onClick="apacheGet"/>  
  38.   
  39.         <Button  
  40.             android:layout_width="wrap_content"  
  41.             android:layout_height="wrap_content"  
  42.             android:text="apache post"   
  43.             android:onClick="apachePost"/>  
  44.     </LinearLayout>  
  45. </LinearLayout>  

AndroidManifest.xml需要添加如下内容:

  1. <uses-permission android:name="android.permission.INTERNET"/>  
java源代码如下:

  1. package com.zhang.test08_01;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.BufferedReader;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.InputStreamReader;  
  9. import java.io.OutputStream;  
  10. import java.io.OutputStreamWriter;  
  11. import java.io.UnsupportedEncodingException;  
  12. import java.io.Writer;  
  13. import java.net.HttpURLConnection;  
  14. import java.net.MalformedURLException;  
  15. import java.net.ProtocolException;  
  16. import java.net.URL;  
  17. import java.net.URLEncoder;  
  18. import java.util.ArrayList;  
  19. import java.util.List;  
  20.   
  21. import org.apache.http.HttpEntity;  
  22. import org.apache.http.HttpResponse;  
  23. import org.apache.http.NameValuePair;  
  24. import org.apache.http.ParseException;  
  25. import org.apache.http.client.ClientProtocolException;  
  26. import org.apache.http.client.HttpClient;  
  27. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  28. import org.apache.http.client.methods.HttpGet;  
  29. import org.apache.http.client.methods.HttpPost;  
  30. import org.apache.http.client.methods.HttpUriRequest;  
  31. import org.apache.http.impl.client.DefaultHttpClient;  
  32. import org.apache.http.message.BasicNameValuePair;  
  33. import org.apache.http.protocol.HTTP;  
  34. import org.apache.http.util.EntityUtils;  
  35.   
  36. import android.app.Activity;  
  37. import android.os.Bundle;  
  38. import android.view.View;  
  39. import android.widget.TextView;  
  40.   
  41. public class Test08_01Activity extends Activity {  
  42.       
  43.     private TextView textView1;  
  44.       
  45.     // You can't use localhost; localhost is the (emulated) phone. You need   
  46.     //to specify the IP address or DNS name of the actual web server.   
  47.     private static final String TEST_URL = "http://192.168.9.194:8080/";  
  48.       
  49.     @Override  
  50.     public void onCreate(Bundle savedInstanceState) {  
  51.         super.onCreate(savedInstanceState);  
  52.         setContentView(R.layout.main);  
  53.           
  54.         textView1 = (TextView)findViewById(R.id.textView1);  
  55.     }  
  56.       
  57.     public void javaGet(View v) {  
  58.         String str = "";  
  59.         try {  
  60.             str = URLEncoder.encode("抓哇""UTF-8");  
  61.         } catch (UnsupportedEncodingException e) {  
  62.         }  
  63.         URL url = null;  
  64.         try {  
  65.             url = new URL(TEST_URL + "?name=javaGet"+str);  
  66.         } catch (MalformedURLException e) {  
  67.         }  
  68.           
  69.         HttpURLConnection urlConnection = null;  
  70.         try {  
  71.             urlConnection = (HttpURLConnection) url.openConnection();  
  72.         } catch (IOException e) {  
  73.             textView1.setText(e.getMessage());  
  74.             return;  
  75.         }  
  76.         //method  The default value is "GET".  
  77.           
  78.         getResponseJava(urlConnection);  
  79.     }  
  80.   
  81.     public void javaPost(View v) {  
  82.         URL url = null;  
  83.         try {  
  84.             url = new URL(TEST_URL);  
  85.         } catch (MalformedURLException e) {  
  86.         }  
  87.           
  88.         HttpURLConnection urlConnection = null;  
  89.         try {  
  90.             urlConnection = (HttpURLConnection) url.openConnection();  
  91.         } catch (IOException e) {  
  92.             textView1.setText(e.getMessage());  
  93.             return;  
  94.         }  
  95.         try {  
  96.             urlConnection.setRequestMethod("POST");  
  97.         } catch (ProtocolException e) {  
  98.         }  
  99.         urlConnection.setDoOutput(true);  
  100.         urlConnection.setRequestProperty("Content-Type""application/x-www-form-urlencoded");  
  101.           
  102.         OutputStream out = null;  
  103.         try {  
  104.             out = new BufferedOutputStream(urlConnection.getOutputStream());//请求  
  105.         } catch (IOException e) {  
  106.             urlConnection.disconnect();  
  107.             textView1.setText(e.getMessage());  
  108.             return;  
  109.         }  
  110.           
  111.         String str = "";  
  112.         try {  
  113.             str = URLEncoder.encode("抓哇""UTF-8");  
  114.         } catch (UnsupportedEncodingException e) {  
  115.         }  
  116.         Writer writer = null;  
  117.         try {  
  118.             writer = new OutputStreamWriter(out,"UTF-8");  
  119.         } catch (UnsupportedEncodingException e1) {  
  120.         }  
  121.         try {  
  122.             writer.write("name=javaPost"+str);  
  123.         } catch (IOException e) {  
  124.             urlConnection.disconnect();  
  125.             textView1.setText(e.getMessage());  
  126.             return;  
  127.         } finally{  
  128.             try {  
  129.                 writer.flush();  
  130.                 writer.close();  
  131.             } catch (IOException e) {  
  132.             }  
  133.         }  
  134.           
  135.         getResponseJava(urlConnection);  
  136.     }  
  137.       
  138.       
  139.     public void apacheGet(View v) {  
  140.         HttpGet request = new HttpGet(TEST_URL + "?name=apacheGet阿帕奇");  
  141.         getResponseApache(request);  
  142.     }  
  143.       
  144.     public void apachePost(View v) {  
  145.         HttpPost request = new HttpPost(TEST_URL);  
  146.           
  147.         List<NameValuePair> params = new ArrayList<NameValuePair>(1);  
  148.         params.add(new BasicNameValuePair("name""apachePost阿帕奇"));  
  149.         HttpEntity formEntity = null;  
  150.         try {  
  151.             formEntity = new UrlEncodedFormEntity(params,HTTP.UTF_8);  
  152.         } catch (UnsupportedEncodingException e) {  
  153.         }  
  154.         request.setEntity(formEntity);  
  155.           
  156.         getResponseApache(request);  
  157.     }  
  158.       
  159.       
  160.     private void getResponseJava(HttpURLConnection urlConnection) {  
  161.         InputStream in = null;  
  162.         try {  
  163.             in = new BufferedInputStream(urlConnection.getInputStream());//响应  
  164.         } catch (IOException e) {  
  165.             urlConnection.disconnect();           
  166.             textView1.setText(e.getMessage());  
  167.             return;  
  168.         }  
  169.           
  170.         BufferedReader reader = null;  
  171.         try {  
  172.             reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));  
  173.         } catch (UnsupportedEncodingException e1) {  
  174.         }  
  175.         StringBuilder result = new StringBuilder();  
  176.         String tmp = null;  
  177.         try {  
  178.             while((tmp = reader.readLine()) != null){  
  179.                 result.append(tmp);  
  180.             }  
  181.         } catch (IOException e) {  
  182.             textView1.setText(e.getMessage());  
  183.             return;  
  184.         } finally {  
  185.             try {  
  186.                 reader.close();  
  187.                 urlConnection.disconnect();  
  188.             } catch (IOException e) {  
  189.             }  
  190.         }  
  191.         textView1.setText(result);  
  192.     }  
  193.       
  194.     private void getResponseApache(HttpUriRequest request) {  
  195.         HttpClient client = new DefaultHttpClient();  
  196.         HttpResponse response = null;  
  197.         try {  
  198.             response = client.execute(request);  
  199.         } catch (ClientProtocolException e) {  
  200.             textView1.setText(e.getMessage());  
  201.         } catch (IOException e) {  
  202.             textView1.setText(e.getMessage());  
  203.         }  
  204.           
  205.         if (response == null) {  
  206.             return;  
  207.         }  
  208.           
  209.         String result = null;  
  210.         if (response.getStatusLine().getStatusCode() == 200) {  
  211.             try {  
  212.                 result = EntityUtils.toString(response.getEntity(),"UTF-8");  
  213.             } catch (ParseException e) {  
  214.                 result = e.getMessage();  
  215.             } catch (IOException e) {  
  216.                 result = e.getMessage();  
  217.             }  
  218.         } else {  
  219.             result = "error response" + response.getStatusLine().toString();  
  220.         }  
  221.         textView1.setText(result);  
  222.     }  
  223. }  
运行起来,看看结果。

先启动node.js服务,在命令行中键入 node example6.js

启动成功

再启动android模拟器


分别点击四个按钮,效果如下:





所有评论
加载评论 ...
发表评论