Node. js + Android HTTP Request Response

Source: Internet
Author: User

This article references
SDK development example (version 2nd)

Last time I made a demo to test how to use node. js to respond to the get POST request and the browser used by the HTTP request. I am learning Android now, so I decided to write a demo that combines the two. Node. js serves as the server to receive get post requests, while Android uses a client to send get post requests.

First, run the node. JS Code (Save As 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 '); // response encoding 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'); // Request Encoding 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 /');

The code is basically the same as the previous one, mainly because the bound address and port have changed (this is very important and I will talk about it later)

Then go to the android source code:

Layout main, XML as follows

<?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 requires the following content:

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

The Java source code is as follows:

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. malform Edurlexception; 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. APAC He. 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; imp ORT 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 S Avedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); textview1 = (textview) findviewbyid (R. id. textview1);} public void javaget (view v) {string STR = ""; try {STR = urlencoder. encode ("catch wow", "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 {o Ut = new bufferedoutputstream (urlconnection. getoutputstream (); // request} catch (ioexception e) {urlconnection. disconnect (); textview1.settext (E. getmessage (); return;} string STR = ""; try {STR = urlencoder. encode ("catch wow", "UTF-8");} catch (unsupportedencodingexception e) {} writer = NULL; try {writer = new outputstreamwriter (Out, "UTF-8 ");} catch (unsupportedencodingexception E1) {} Try {writer. write ("n Ame = 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 Apache "); 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 Apache"); httpentity formentity = NULL; try {formentity = new urlencodedformentity (Params, HTTP. utf_8);} catch (unsupportedencodingexception e) {} request. setentit Y (formentity); getresponseapache (request);} private void getresponsejava (httpurlconnection urlconnection) {inputstream in = NULL; try {In = new bufferedinputstream (urlconnection. getinputstream (); // response} 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.exe cute (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 );}}

Run it and check the result.

Start the node. js service and type node example6.js in the command line.

Started successfully

Start the android simulator again

Click the following four buttons:

What impressed me most during the whole process was that the address I began to bind and access was localhost: 8080, which could never be accessed. Then I found myself too Sb on the Internet.

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

Key words: 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.

I forgot a very important thing. the Java Virtual Machine started during code Runtime is on the android simulator, and the localhost is the simulator...

Note that the code written by Android accesses the local file system or network environment on the simulator.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.