Interaction between Android and Servlet JSON data

Source: Internet
Author: User
Android customers

Package COM. comingx. xzz; import Org. apache. HTTP. httpresponse; import Org. apache. HTTP. client. httpclient; import Org. apache. HTTP. client. methods. httppost; import Org. apache. HTTP. entity. stringentity; import Org. apache. HTTP. impl. client. defaulthttpclient; import Org. apache. HTTP. util. entityutils; import Org. JSON. jsonobject; import android. app. activity; import android. app. progressdialog; import android. OS. asynctas K; import android. OS. bundle; import android. util. log; import android. view. view; import android. widget. button; import android. widget. edittext; public class main extends activity {Private Static final string tag = "Main"; private edittext nameedit; private edittext phoneedit; private edittext resultedit; private button sendbtn; private progressdialog; @ overridepublic void oncreate (bundle saved Instancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); nameedit = (edittext) findviewbyid (R. id. name); phoneedit = (edittext) findviewbyid (R. id. phone); resultedit = (edittext) findviewbyid (R. id. result); sendbtn = (button) findviewbyid (R. id. sendbtn); progressdialog = new progressdialog (this); sendbtn. setonclicklistener (New button. onclicklistener () {@ overridepublic void onclick (View v) {New at(cmd.exe cute (nameedit. gettext (). tostring (), phoneedit. gettext (). tostring () ;}});} class at extends asynctask {@ overrideprotected void onpreexecute () {progressdialog. show () ;}@ overrideprotected string doinbackground (string... params) {try {// request data httpclient Hc = new defaulthttpclient (); httppost HP = new httppost ("http: // 192.168.1.102: 8080/jsonservlet "); // request JSON message jsonobject Jo = new jsonobject (); If (Params. length> 1) {Jo. put ("name", Params [0]); Jo. put ("phone", Params [1]);} else {Jo. put ("Err", "error");} log. D (TAG, "Params:" + Jo. tostring (); HP. setentity (New stringentity (Jo. tostring (); httpresponse hR = hc.exe cute (HP); string result = NULL; // obtain the returned JSON packet if (HR. getstatusline (). getstatuscode () = 200) {result = entityutils. tostring (HR. getentity (); log. D (TAG, "Result:" + Result);} // close the connection if (HC! = NULL) {HC. getconnectionmanager (). shutdown ();} return result;} catch (exception e) {e. printstacktrace (); return NULL ;}@overrideprotected void onpostexecute (string result) {resultedit. settext (result); progressdialog. cancel ();}}}

Server code:
Package COM. comingx. xzz; import Java. io. bufferedreader; import Java. io. datainputstream; import Java. io. dataoutputstream; import Java. io. ioexception; import Java. io. inputstreamreader; import Java. io. printwriter; import Java. util. enumeration; import javax. servlet. servletexception; import javax. servlet. servletinputstream; import javax. servlet. HTTP. httpservlet; import javax. servlet. HTTP. httpservletrequest; impor T javax. servlet. HTTP. dependencies;/*** Servlet implementation class jsonservlet */public class jsonservlet extends httpservlet {Private Static final long serialversionuid = 1l; @ overrideprotected void dopost (httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {string result = ""; try {/* read data */bufferedreader BR = new bufferedreader (New inputstreamreader (( Servletinputstream) Req. getinputstream (), "UTF-8"); stringbuffer sb = new stringbuffer (""); string temp; while (temp = Br. Readline ())! = NULL) {sb. append (temp);} BR. close (); Result = sb. tostring (); system. out. println ("request message:" + result);} catch (exception e) {result = "{err: \" error \"}";} finally {/* returned data */system. out. println ("Returned message:" + result); printwriter PW = resp. getwriter (); PW. write (result); PW. flush (); PW. close ();}}}

The server has only one servlet for processing.

The code is obvious.

Android uses Apache's httpclient for network connection. It stores JSON data in stringentity and sets the object setentity () of httppost (). Use httpclient to implement network requests, then obtain the data result = entityutils. tostirng (HR. getentity (), and display the results on edittext.

The server code is also very simple.

Use bufferreader to block the inputstream obtained from request to read the Request Entity, obtain the request JSON message, and return it to the client in the output stream of the message result.

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.