http://www.linuxidc.com/Linux/2012-02/53539.htm


上次做了一个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. varhttp=require('http');
  2. varserver=http.createServer();
  3. varquerystring=require('querystring');
  4. varpostResponse=function(req,res){
  5. varinfo='';
  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('HelloWorldPOST'+info.name,'utf8');
  13. })
  14. }
  15. vargetResponse=function(req,res){
  16. res.writeHead(200,{'Content-Type':'text/plain'});
  17. varname=require('url').parse(req.url,true).query.name
  18. res.end('HelloWorldGET'+name,'utf8');
  19. }
  20. varrequestFunction=function(req,res){
  21. req.setEncoding('utf8');//请求编码
  22. if(req.method=='POST'){
  23. returnpostResponse(req,res);
  24. }
  25. returngetResponse(req,res);
  26. }
  27. server.on('request',requestFunction);
  28. server.listen(8080,"192.168.9.194");
  29. console.log('Serverrunningathttp://192.168.9.194:8080/');
代码基本和上次一样,主要是绑定的地址和端口变了(这个很重要,后边再讲)

再上android源代码:

layout main,xml如下

[html]
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns: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="javaget"
  17. android:onClick="javaGet"/>
  18. <Button
  19. android:layout_width="wrap_content"
  20. android:layout_height="wrap_content"
  21. android:text="javapost"
  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="apacheget"
  31. android:onClick="apacheGet"/>
  32. <Button
  33. android:layout_width="wrap_content"
  34. android:layout_height="wrap_content"
  35. android:text="apachepost"
  36. android:onClick="apachePost"/>
  37. </LinearLayout>
  38. </LinearLayout>
AndroidManifest.xml需要添加如下内容:

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

[java]
  1. packagecom.zhang.test08_01;
  2. importjava.io.BufferedInputStream;
  3. importjava.io.BufferedOutputStream;
  4. importjava.io.BufferedReader;
  5. importjava.io.IOException;
  6. importjava.io.InputStream;
  7. importjava.io.InputStreamReader;
  8. importjava.io.OutputStream;
  9. importjava.io.OutputStreamWriter;
  10. importjava.io.UnsupportedEncodingException;
  11. importjava.io.Writer;
  12. importjava.net.HttpURLConnection;
  13. importjava.net.MalformedURLException;
  14. importjava.net.ProtocolException;
  15. importjava.net.URL;
  16. importjava.net.URLEncoder;
  17. importjava.util.ArrayList;
  18. importjava.util.List;
  19. importorg.apache.http.HttpEntity;
  20. importorg.apache.http.HttpResponse;
  21. importorg.apache.http.NameValuePair;
  22. importorg.apache.http.ParseException;
  23. importorg.apache.http.client.ClientProtocolException;
  24. importorg.apache.http.client.HttpClient;
  25. importorg.apache.http.client.entity.UrlEncodedFormEntity;
  26. importorg.apache.http.client.methods.HttpGet;
  27. importorg.apache.http.client.methods.HttpPost;
  28. importorg.apache.http.client.methods.HttpUriRequest;
  29. importorg.apache.http.impl.client.DefaultHttpClient;
  30. importorg.apache.http.message.BasicNameValuePair;
  31. importorg.apache.http.protocol.HTTP;
  32. importorg.apache.http.util.EntityUtils;
  33. importandroid.app.Activity;
  34. importandroid.os.Bundle;
  35. importandroid.view.View;
  36. importandroid.widget.TextView;
  37. publicclassTest08_01ActivityextendsActivity{
  38. privateTextViewtextView1;
  39. //Youcan'tuselocalhost;localhostisthe(emulated)phone.Youneed
  40. //tospecifytheIPaddressorDNSnameoftheactualwebserver.
  41. privatestaticfinalStringTEST_URL="http://192.168.9.194:8080/";
  42. @Override
  43. publicvoidonCreate(BundlesavedInstanceState){
  44. super.onCreate(savedInstanceState);
  45. setContentView(R.layout.main);
  46. textView1=(TextView)findViewById(R.id.textView1);
  47. }
  48. publicvoidjavaGet(Viewv){
  49. Stringstr="";
  50. try{
  51. str=URLEncoder.encode("抓哇","UTF-8");
  52. }catch(UnsupportedEncodingExceptione){
  53. }
  54. URLurl=null;
  55. try{
  56. url=newURL(TEST_URL+"?name=javaGet"+str);
  57. }catch(MalformedURLExceptione){
  58. }
  59. HttpURLConnectionurlConnection=null;
  60. try{
  61. urlConnection=(HttpURLConnection)url.openConnection();
  62. }catch(IOExceptione){
  63. textView1.setText(e.getMessage());
  64. return;
  65. }
  66. //methodThedefaultvalueis"GET".
  67. getResponseJava(urlConnection);
  68. }
  69. publicvoidjavaPost(Viewv){
  70. URLurl=null;
  71. try{
  72. url=newURL(TEST_URL);
  73. }catch(MalformedURLExceptione){
  74. }
  75. HttpURLConnectionurlConnection=null;
  76. try{
  77. urlConnection=(HttpURLConnection)url.openConnection();
  78. }catch(IOExceptione){
  79. textView1.setText(e.getMessage());
  80. return;
  81. }
  82. try{
  83. urlConnection.setRequestMethod("POST");
  84. }catch(ProtocolExceptione){
  85. }
  86. urlConnection.setDoOutput(true);
  87. urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
  88. OutputStreamout=null;
  89. try{
  90. out=newBufferedOutputStream(urlConnection.getOutputStream());//请求
  91. }catch(IOExceptione){
  92. urlConnection.disconnect();
  93. textView1.setText(e.getMessage());
  94. return;
  95. }
  96. Stringstr="";
  97. try{
  98. str=URLEncoder.encode("抓哇","UTF-8");
  99. }catch(UnsupportedEncodingExceptione){
  100. }
  101. Writerwriter=null;
  102. try{
  103. writer=newOutputStreamWriter(out,"UTF-8");
  104. }catch(UnsupportedEncodingExceptione1){
  105. }
  106. try{
  107. writer.write("name=javaPost"+str);
  108. }catch(IOExceptione){
  109. urlConnection.disconnect();
  110. textView1.setText(e.getMessage());
  111. return;
  112. }finally{
  113. try{
  114. writer.flush();
  115. writer.close();
  116. }catch(IOExceptione){
  117. }
  118. }
  119. getResponseJava(urlConnection);
  120. }
  121. publicvoidapacheGet(Viewv){
  122. HttpGetrequest=newHttpGet(TEST_URL+"?name=apacheGet阿帕奇");
  123. getResponseApache(request);
  124. }
  125. publicvoidapachePost(Viewv){
  126. HttpPostrequest=newHttpPost(TEST_URL);
  127. List<NameValuePair>params=newArrayList<NameValuePair>(1);
  128. params.add(newBasicNameValuePair("name","apachePost阿帕奇"));
  129. HttpEntityformEntity=null;
  130. try{
  131. formEntity=newUrlEncodedFormEntity(params,HTTP.UTF_8);
  132. }catch(UnsupportedEncodingExceptione){
  133. }
  134. request.setEntity(formEntity);
  135. getResponseApache(request);
  136. }
  137. privatevoidgetResponseJava(HttpURLConnectionurlConnection){
  138. InputStreamin=null;
  139. try{
  140. in=newBufferedInputStream(urlConnection.getInputStream());//响应
  141. }catch(IOExceptione){
  142. urlConnection.disconnect();
  143. textView1.setText(e.getMessage());
  144. return;
  145. }
  146. BufferedReaderreader=null;
  147. try{
  148. reader=newBufferedReader(newInputStreamReader(in,"UTF-8"));
  149. }catch(UnsupportedEncodingExceptione1){
  150. }
  151. StringBuilderresult=newStringBuilder();
  152. Stringtmp=null;
  153. try{
  154. while((tmp=reader.readLine())!=null){
  155. result.append(tmp);
  156. }
  157. }catch(IOExceptione){
  158. textView1.setText(e.getMessage());
  159. return;
  160. }finally{
  161. try{
  162. reader.close();
  163. urlConnection.disconnect();
  164. }catch(IOExceptione){
  165. }
  166. }
  167. textView1.setText(result);
  168. }
  169. privatevoidgetResponseApache(HttpUriRequestrequest){
  170. HttpClientclient=newDefaultHttpClient();
  171. HttpResponseresponse=null;
  172. try{
  173. response=client.execute(request);
  174. }catch(ClientProtocolExceptione){
  175. textView1.setText(e.getMessage());
  176. }catch(IOExceptione){
  177. textView1.setText(e.getMessage());
  178. }
  179. if(response==null){
  180. return;
  181. }
  182. Stringresult=null;
  183. if(response.getStatusLine().getStatusCode()==200){
  184. try{
  185. result=EntityUtils.toString(response.getEntity(),"UTF-8");
  186. }catch(ParseExceptione){
  187. result=e.getMessage();
  188. }catch(IOExceptione){
  189. result=e.getMessage();
  190. }
  191. }else{
  192. result="errorresponse"+response.getStatusLine().toString();
  193. }
  194. textView1.setText(result);
  195. }
  196. }

更多相关文章

  1. android 权限封装(思路来至于RxPermissions)
  2. retrofit2+okhttp3+rxjava网络封装
  3. Android入门进阶教程(13)-ServiceManager服务管理详解
  4. Android(安卓)OkHttp, 一行代码 OkHttp提升请求稳定性
  5. ListView的Item中有CheckBox,导致OnItemClick不响应的解决办法
  6. android Java 提交数据到服务器的两种方式中四种方法
  7. Android中通过其他APP启动Activity的四种方式
  8. react-native 0.62 fetch请求上传图片失败 ----------小白的天堂
  9. Android(安卓)时间更新机制之网络更新时间

随机推荐

  1. win10 编译 Android(安卓)ffmpeg
  2. Android(安卓)各种音量的获取和设置
  3. Android(安卓)Studio常用快捷键、Android
  4. Android上层启动过程的几个关键点
  5. Android(安卓)android:exported = true
  6. Android(安卓)HttpURLConnection应用技巧
  7. Android(安卓)Opencore
  8. Android属性之build.prop,及property_get/
  9. Android系统启动流程 -4
  10. 使用WebView中的JavaScript调用Android方