node.js+Android(安卓)http请求响应
16lz
2021-01-26
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]
- varhttp=require('http');
- varserver=http.createServer();
- varquerystring=require('querystring');
- varpostResponse=function(req,res){
- varinfo='';
- 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('HelloWorldPOST'+info.name,'utf8');
- })
- }
- vargetResponse=function(req,res){
- res.writeHead(200,{'Content-Type':'text/plain'});
- varname=require('url').parse(req.url,true).query.name
- res.end('HelloWorldGET'+name,'utf8');
- }
- varrequestFunction=function(req,res){
- req.setEncoding('utf8');//请求编码
- if(req.method=='POST'){
- returnpostResponse(req,res);
- }
- returngetResponse(req,res);
- }
- server.on('request',requestFunction);
- server.listen(8080,"192.168.9.194");
- console.log('Serverrunningathttp://192.168.9.194:8080/');
再上android源代码:
layout main,xml如下
[html]
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns: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="javaget"
- android:onClick="javaGet"/>
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="javapost"
- 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="apacheget"
- android:onClick="apacheGet"/>
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="apachepost"
- android:onClick="apachePost"/>
- </LinearLayout>
- </LinearLayout>
[html]
- <uses-permissionandroid:name="android.permission.INTERNET"/>
[java]
- packagecom.zhang.test08_01;
- importjava.io.BufferedInputStream;
- importjava.io.BufferedOutputStream;
- importjava.io.BufferedReader;
- importjava.io.IOException;
- importjava.io.InputStream;
- importjava.io.InputStreamReader;
- importjava.io.OutputStream;
- importjava.io.OutputStreamWriter;
- importjava.io.UnsupportedEncodingException;
- importjava.io.Writer;
- importjava.net.HttpURLConnection;
- importjava.net.MalformedURLException;
- importjava.net.ProtocolException;
- importjava.net.URL;
- importjava.net.URLEncoder;
- importjava.util.ArrayList;
- importjava.util.List;
- importorg.apache.http.HttpEntity;
- importorg.apache.http.HttpResponse;
- importorg.apache.http.NameValuePair;
- importorg.apache.http.ParseException;
- importorg.apache.http.client.ClientProtocolException;
- importorg.apache.http.client.HttpClient;
- importorg.apache.http.client.entity.UrlEncodedFormEntity;
- importorg.apache.http.client.methods.HttpGet;
- importorg.apache.http.client.methods.HttpPost;
- importorg.apache.http.client.methods.HttpUriRequest;
- importorg.apache.http.impl.client.DefaultHttpClient;
- importorg.apache.http.message.BasicNameValuePair;
- importorg.apache.http.protocol.HTTP;
- importorg.apache.http.util.EntityUtils;
- importandroid.app.Activity;
- importandroid.os.Bundle;
- importandroid.view.View;
- importandroid.widget.TextView;
- publicclassTest08_01ActivityextendsActivity{
- privateTextViewtextView1;
- //Youcan'tuselocalhost;localhostisthe(emulated)phone.Youneed
- //tospecifytheIPaddressorDNSnameoftheactualwebserver.
- privatestaticfinalStringTEST_URL="http://192.168.9.194:8080/";
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- textView1=(TextView)findViewById(R.id.textView1);
- }
- publicvoidjavaGet(Viewv){
- Stringstr="";
- try{
- str=URLEncoder.encode("抓哇","UTF-8");
- }catch(UnsupportedEncodingExceptione){
- }
- URLurl=null;
- try{
- url=newURL(TEST_URL+"?name=javaGet"+str);
- }catch(MalformedURLExceptione){
- }
- HttpURLConnectionurlConnection=null;
- try{
- urlConnection=(HttpURLConnection)url.openConnection();
- }catch(IOExceptione){
- textView1.setText(e.getMessage());
- return;
- }
- //methodThedefaultvalueis"GET".
- getResponseJava(urlConnection);
- }
- publicvoidjavaPost(Viewv){
- URLurl=null;
- try{
- url=newURL(TEST_URL);
- }catch(MalformedURLExceptione){
- }
- HttpURLConnectionurlConnection=null;
- try{
- urlConnection=(HttpURLConnection)url.openConnection();
- }catch(IOExceptione){
- textView1.setText(e.getMessage());
- return;
- }
- try{
- urlConnection.setRequestMethod("POST");
- }catch(ProtocolExceptione){
- }
- urlConnection.setDoOutput(true);
- urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
- OutputStreamout=null;
- try{
- out=newBufferedOutputStream(urlConnection.getOutputStream());//请求
- }catch(IOExceptione){
- urlConnection.disconnect();
- textView1.setText(e.getMessage());
- return;
- }
- Stringstr="";
- try{
- str=URLEncoder.encode("抓哇","UTF-8");
- }catch(UnsupportedEncodingExceptione){
- }
- Writerwriter=null;
- try{
- writer=newOutputStreamWriter(out,"UTF-8");
- }catch(UnsupportedEncodingExceptione1){
- }
- try{
- writer.write("name=javaPost"+str);
- }catch(IOExceptione){
- urlConnection.disconnect();
- textView1.setText(e.getMessage());
- return;
- }finally{
- try{
- writer.flush();
- writer.close();
- }catch(IOExceptione){
- }
- }
- getResponseJava(urlConnection);
- }
- publicvoidapacheGet(Viewv){
- HttpGetrequest=newHttpGet(TEST_URL+"?name=apacheGet阿帕奇");
- getResponseApache(request);
- }
- publicvoidapachePost(Viewv){
- HttpPostrequest=newHttpPost(TEST_URL);
- List<NameValuePair>params=newArrayList<NameValuePair>(1);
- params.add(newBasicNameValuePair("name","apachePost阿帕奇"));
- HttpEntityformEntity=null;
- try{
- formEntity=newUrlEncodedFormEntity(params,HTTP.UTF_8);
- }catch(UnsupportedEncodingExceptione){
- }
- request.setEntity(formEntity);
- getResponseApache(request);
- }
- privatevoidgetResponseJava(HttpURLConnectionurlConnection){
- InputStreamin=null;
- try{
- in=newBufferedInputStream(urlConnection.getInputStream());//响应
- }catch(IOExceptione){
- urlConnection.disconnect();
- textView1.setText(e.getMessage());
- return;
- }
- BufferedReaderreader=null;
- try{
- reader=newBufferedReader(newInputStreamReader(in,"UTF-8"));
- }catch(UnsupportedEncodingExceptione1){
- }
- StringBuilderresult=newStringBuilder();
- Stringtmp=null;
- try{
- while((tmp=reader.readLine())!=null){
- result.append(tmp);
- }
- }catch(IOExceptione){
- textView1.setText(e.getMessage());
- return;
- }finally{
- try{
- reader.close();
- urlConnection.disconnect();
- }catch(IOExceptione){
- }
- }
- textView1.setText(result);
- }
- privatevoidgetResponseApache(HttpUriRequestrequest){
- HttpClientclient=newDefaultHttpClient();
- HttpResponseresponse=null;
- try{
- response=client.execute(request);
- }catch(ClientProtocolExceptione){
- textView1.setText(e.getMessage());
- }catch(IOExceptione){
- textView1.setText(e.getMessage());
- }
- if(response==null){
- return;
- }
- Stringresult=null;
- if(response.getStatusLine().getStatusCode()==200){
- try{
- result=EntityUtils.toString(response.getEntity(),"UTF-8");
- }catch(ParseExceptione){
- result=e.getMessage();
- }catch(IOExceptione){
- result=e.getMessage();
- }
- }else{
- result="errorresponse"+response.getStatusLine().toString();
- }
- textView1.setText(result);
- }
- }
更多相关文章
- android 权限封装(思路来至于RxPermissions)
- retrofit2+okhttp3+rxjava网络封装
- Android入门进阶教程(13)-ServiceManager服务管理详解
- Android(安卓)OkHttp, 一行代码 OkHttp提升请求稳定性
- ListView的Item中有CheckBox,导致OnItemClick不响应的解决办法
- android Java 提交数据到服务器的两种方式中四种方法
- Android中通过其他APP启动Activity的四种方式
- react-native 0.62 fetch请求上传图片失败 ----------小白的天堂
- Android(安卓)时间更新机制之网络更新时间