歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> node.js+Android http請求響應

node.js+Android http請求響應

日期:2017/3/1 10:33:51   编辑:Linux編程

上次做了一個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]
  1. var http = require('http');
  2. var server = http.createServer();
  3. var querystring = require('querystring');
  4. var postResponse = function(req, res) {
  5. var info ='';
  6. req.addListener('data', function(chunk){
  7. info += chunk;
  8. })
  9. .addListener('end', function(){
  10. info = querystring.parse(info);
  11. res.setHeader('content-type','text/html; charset=UTF-8');//響應編碼
  12. res.end('Hello World POST ' + info.name,'utf8');
  13. })
  14. }
  15. var getResponse = function (req, res){
  16. res.writeHead(200, {'Content-Type': 'text/plain'});
  17. var name = require('url').parse(req.url,true).query.name
  18. res.end('Hello World GET ' + name,'utf8');
  19. }
  20. var requestFunction = function (req, res){
  21. req.setEncoding('utf8');//請求編碼
  22. if (req.method == 'POST'){
  23. return postResponse(req, res);
  24. }
  25. return getResponse(req, res);
  26. }
  27. server.on('request',requestFunction);
  28. server.listen(8080, "192.168.9.194");
  29. console.log('Server running at http://192.168.9.194:8080/');
代碼基本和上次一樣,主要是綁定的地址和端口變了(這個很重要,後邊再講)

再上android源代碼:

layout main,xml如下

[html]
  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. <TextView
  7. android:id="@+id/textView1"
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"/>
  10. <LinearLayout
  11. android:layout_width="match_parent"
  12. android:layout_height="wrap_content" >
  13. <Button
  14. android:layout_width="wrap_content"
  15. android:layout_height="wrap_content"
  16. android:text="java get"
  17. android:onClick="javaGet"/>
  18. <Button
  19. android:layout_width="wrap_content"
  20. android:layout_height="wrap_content"
  21. android:text="java post"
  22. android:onClick="javaPost"/>
  23. </LinearLayout>
  24. <LinearLayout
  25. android:layout_width="match_parent"
  26. android:layout_height="wrap_content" >
  27. <Button
  28. android:layout_width="wrap_content"
  29. android:layout_height="wrap_content"
  30. android:text="apache get"
  31. android:onClick="apacheGet"/>
  32. <Button
  33. android:layout_width="wrap_content"
  34. android:layout_height="wrap_content"
  35. android:text="apache post"
  36. android:onClick="apachePost"/>
  37. </LinearLayout>
  38. </LinearLayout>
AndroidManifest.xml需要添加如下內容:

[html]
  1. <uses-permission android:name="android.permission.INTERNET"/>
java源代碼如下:

[java]

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