Android and server-side data interaction (HTTP protocol Integration struts2+android)

Source: Internet
Author: User

In Android sometimes we do not need to use the native SQLite database to provide data, more often from the network to obtain data, then how to get the data from the server side of Android? There are many kinds of, summed up there

One: Get the data method based on the HTTP protocol. Second: The method of acquiring data based on SAOP protocol, three: forget-------

So our article is mainly about using the HTTP protocol to obtain server-side data, here we take the server-side technology is Java, the framework is Struts2, or can have servlets, or can be directly from the JSP page to get data.

So, let's start this journey:

First: To write a server-side approach, I use the MVC framework here is STRUTS2, the purpose is simple, is to do a complete business project in the future, technology equipped as: Android+ssh. Of course, the space is limited, I use STRTUS2 directly here.

server-side : New WebProject, select Java EE 5.0.

In order to add STRUTS2 support to the project, we have to import some of the Struts2 class libraries, such as the following (some jar packages are not necessary, but we can later extend it to be used, we will first get in):

1:xwork-core-2.2.1. 1.jar

2:struts2-core-2.2.1. 1.jar

3:commons-logging-1.0.4. Jar

4:freemarker-2.3.16. Jar

5:ognl-3.0.jar

6:javassist-3.7.ga.jar

7:commons-ileupload.jar

8:commons-io.jar

9:json-lib-2.1-jdk15.jar processing JSON format data to use to

10:struts2-json-plugin-2.2.1. 1.jar STRUTS2-based JSON plug -in

The above jar packages need to be placed in the Webroot/web-inf/lib directory

Then, in the Web. xml file, knock down:

<?xml version="1.0"encoding="UTF-8"? ><web-app version="2.5"xmlns="Http://java.sun.com/xml/ns/javaee"Xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation="Http://java.sun.com/xml/ns/javaeehttp//java.sun.com/xml/ns/javaee/web-app_2_5.xsd "><!--define STRUTS2 's core controller: Filterdispatcher--<filter> <!--define the name of the core filter--<filter-name >struts2</filter-name> <!--defining the implementation class for filter--<filter-class>org.apache.struts2.dispatcher.filterdispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-p Attern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</w elcome-file> </welcome-file-list> </web-app>

Then write the Struts.xml file, and put it in the Webroot/web-inf/lib directory: The following code:

<?xml version="1.0"encoding="UTF-8"? ><!DOCTYPE Struts public"-//apache software foundation//dtd Struts Configuration 2.0//en"    "HTTP://STRUTS.APACHE.ORG/DTDS/STRUTS-2.0.DTD"> <struts> <!--setting Encoding,dynamicmethod,language<constant name="struts.custom.i18n.resources"Value="Messageresource"></constant> <constant name="struts.i18n.encoding"Value="UTF-8"></constant> <constant name="struts.enable.DynamicMethodInvocation"Value="true"></constant> <!--Add package here extends="Struts-default"-<package Name="Dongzi"extends="Json-default"> <!--need to change Struts-default to json-default-<!--setting action---<action name="Login" class="com.dongzi.action.loginAction"Method="Login"> <result type="JSON"></result> <!--return value type set to JSON, do not set the return page--</action> </package> &LT;/STRUTS&G T

Once configured, we then write the action based on the <action> tag content. The method corresponds to the login, the class name is Loginaction,

Note: Package inheritance is: Json-default, the output type is JSON as follows:

 Public classLoginaction extends Actionsupport implements Servletrequestaware,servletresponseaware { /c2>/**     *      */    Private StaticFinalLongSerialversionuid =1L;    HttpServletRequest request;    HttpServletResponse response;  Public voidsetservletrequest (HttpServletRequest request) { This. request=request; }     Public voidSetservletresponse (httpservletresponse response) { This. response=response; }     Public voidLogin () {Try {             //httpservletrequest request =servletactioncontext.getrequest (); //httpservletresponse response=servletactioncontext.getresponse ();              This. Response.setcontenttype ("Text/html;charset=utf-8");  This. response.setcharacterencoding ("UTF-8"); if( This. Request.getparameter ("username"). Equals ("123456")){                       This. Response.getwriter (). Write ("It's really weird, Japanese! "); }Else if( This. Request.getparameter ("username"). Equals ("Zhd")){                      This. Response.getwriter (). Write ("There is no mistake, I am tungse brother! "); }Else{                      This. Response.getwriter (). Write ("I'm Tungse! "); }                             //JSON processing of entity objects that will be returned//jsonobject Json=jsonobject.fromobject (This.getusername ()); //output format such as: {"id": 1, "username": "Zhangsan", "pwd": "123"}//System.out.println (JSON); //this.response.getWriter (). Write (json.tostring ());            /** Jsonobject json=new jsonobject ();                Json.put ("Login", "login");               Response.setcontenttype ("Text/html;charset=utf-8");               SYSTEM.OUT.PRINTLN (JSON);               byte[] jsonbytes = json.tostring (). GetBytes ("Utf-8");               Response.setcontentlength (jsonbytes.length);               Response.getoutputstream (). write (jsonbytes); **/            /** Jsonobject json=new jsonobject ();               Json.put ("Login", "login");               byte[] jsonbytes = json.tostring (). GetBytes ("Utf-8");               Response.setcontenttype ("Text/html;charset=utf-8");               Response.setcontentlength (jsonbytes.length);               Response.getoutputstream (). write (jsonbytes);               Response.getoutputstream (). Flush ();                 Response.getoutputstream (). Close (); **/                       } Catch(Exception e) {e.printstacktrace (); }        //return null;    }}

Client:

It is important to note that the simulator treats itself as localhost, and 127.0.0.1, so if you are testing based on a local Web project, you must modify the IP to: 10.0.2.2

 Public classMainactivity extends Activity {/** Called when the activity is first created.*/ //simulator itself as a localhost, the server should be 10.0.2.2 Private StaticString url="http://10.0.2.2:8080/PDAServer/login.action"; @Override Public voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.main);     Getpdaserverdata (URL); }        /** * Request service * @param URL*/    Private voidgetpdaserverdata (String url) {URL+="? username=123456"; HttpClient Client=Newdefaulthttpclient ();      HttpPost request; Try{Request=NewHttpPost (NewURI (URL)); HttpResponse Response=Client.execute (Request); //determine if the request was successful      if(Response.getstatusline (). Getstatuscode () = = $) {httpentity entity=response.getentity (); if(entity!=NULL) {String out=entityutils.tostring (entity); NewAlertdialog.builder ( This). Setmessage ( out). Create (). Show (); }      }     }Catch(URISyntaxException e) {e.printstacktrace (); }     Catch(clientprotocolexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }    } }

The results of the operation are as follows:

Android and server-side data interaction (HTTP protocol Integration struts2+android)

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.