node.js+android http請求響應

來源:互聯網
上載者:User

本文參照了 http://www.blogjava.net/jelver/articles/143082.html,http://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):

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如下

<?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需要添加如下內容:

<uses-permission android:name="android.permission.INTERNET"/>

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);}}

運行起來,看看結果。

先啟動node.js服務,在命令列中鍵入 node example6.js

啟動成功

再啟動android模擬器

分別點擊四個按鈕,效果如下:

整個過程最讓我暈倒的是,我開始綁定和訪問的地址是localhost:8080,可以一直無法訪問,後來上網找了以下,發現自己太SB了

http://groups.google.com/group/android-developers/browse_thread/thread/801645febf0523ea

關鍵這句話: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. 

我忘了一件很重要的事,My Code運行時啟動的java虛擬機器是在android模擬器上,localhost是模擬器啊。。。

以後要注意啊,android寫的代碼訪問的本地檔案系統或者網路環境等都是在模擬器上。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.