How the Android client interacts with the server-summary

Source: Internet
Author: User

The recent Android project development process has plagued itself for a long time, and the Android client interacts with the server in several ways, the most common being webservices and JSON. To interact with the PC server on the Android phone client, you need to meet the following criteria: cross-platform, data format standard, interactive convenience.

In order to communicate with the server is nothing but two protocols http and Tcp,tcp learning socket,http words familiar with the HTTP protocol and related Java API. The following are some of the ways to extend from the two protocols: WebServices soap, SSH JSON (refer to: The link), Xmlrpc (WordPress for Android) ...

Socket is not recommended, HTTP RESTful recommended . with the server to transmit data, it is generally used in the RESTful API to transport. First of all, there is a preliminary understanding of the HTTP protocol, at least know what the difference between get/post.

If there is no special requirement, it is simpler and more common to use webservices to transfer XML files , and JSON is more appropriate if the data size and transmission speed are required.

"The difference between a socket and an HTTP connection"

The HTTP connection uses a "request-response" approach that requires the server to reply to the data, not only when the request is made, but also when the client requests the server.

The socket is capable of listening, so once the socket connection is established, the communication parties can start sending data content to each other until the two sides are disconnected. Keep the client and server data in real time and in sync.

XML RPC is an RPC mechanism that uses the HTTP protocol as a transport protocol to transfer commands and data in the form of XML literals.

RPC is the abbreviation of remote Procedure call, translated into Chinese is a long-distance procedure calls, is a local machine on the remote machine to invoke a process (method) technology, this process is called "distributed computing"

There are many examples on the web to demonstrate how Android client and server-side data interact. But these examples are mostly cumbersome, which is unfavorable for beginners, and now introduces a simple, logically clear example of interaction:

To transfer an XML file using WebServices:

First, server-side:

Code Listing 1: Adding a file named ""

1  PackageCom.ghj.packageofservlet;2  3;4;5  6 Importjavax.servlet.ServletException;7 ImportJavax.servlet.http.HttpServlet;8 Importjavax.servlet.http.HttpServletRequest;9 ImportJavax.servlet.http.HttpServletResponse;Ten   One  Public classAndroidserverservletextendsHttpServlet { A   -     Private Static Final LongSerialversionuid = 6792396567928634227L; -   the      Public voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException { -Response.setcontenttype (Text/plain; charset=utf-8); -Request.setcharacterencoding (UTF-8); - System.err.println (Request.getparameter (Clientdata)); +PrintWriter PrintWriter =Response.getwriter (); - printwriter.print (Hello Android client!) ); + Printwriter.flush (); A printwriter.close (); at     } -}

Code Listing 2: Modifying a file named "Web. Xml"

1<!--? XML version=1.0 encoding=utf-8?-->2<web-app http:= "" javaee= "ns=" version= "2.5" web-app_2_5.xsd= "xml=" xmlns= " Ns/javaee "xmlns:xsi=" "xsi:schemalocation=" Java ee "><servlet>3<servlet-name>AndroidServerServlet</servlet-name>4<servlet-class>com.ghj.packageofservlet.androidserverservlet</servlet-class>5</servlet>6  7<servlet-mapping>8<servlet-name>AndroidServerServlet</servlet-name>9<url-pattern>/AndroidServerServlet</url-pattern>Ten</servlet-mapping> One</web-app>

Second, Android mobile phone client:

Code Listing 1: Adding a file named ""

1  Packagecom.example.androidclient;2  3;4;5 Importjava.util.ArrayList;6 Importjava.util.List;7  8 ImportOrg.apache.http.HttpResponse;9 ImportOrg.apache.http.NameValuePair;Ten Importorg.apache.http.client.ClientProtocolException; One Importorg.apache.http.client.HttpClient; A Importorg.apache.http.client.entity.UrlEncodedFormEntity; - ImportOrg.apache.http.client.methods.HttpPost; - Importorg.apache.http.impl.client.DefaultHttpClient; the ImportOrg.apache.http.message.BasicNameValuePair; - ImportOrg.apache.http.protocol.HTTP; - Importorg.apache.http.util.EntityUtils; -   +; - ImportAndroid.os.Bundle; + ImportAndroid.os.Handler; A ImportAndroid.os.Message; at ImportAndroid.view.View; - ImportAndroid.view.View.OnClickListener; - ImportAndroid.widget.Button; - ImportAndroid.widget.Toast; -   -  Public classAndroidclientactivityextendsActivity { in       - @Override to     protected voidonCreate (Bundle savedinstancestate) { +         Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.android_client); the   *Button Sendbutton =(Button) Findviewbyid (; $Sendbutton.setonclicklistener (NewOnclicklistener () {Panax Notoginseng @Override -              Public voidOnClick (View v) { the                 NewThread (NewRunnable () { + @Override A                      Public voidrun () { theHttpPost HttpRequest =NewHttpPost (; +list<namevaluepair> params =NewArraylist<namevaluepair>(); -Params.add (NewBasicnamevaluepair (clientdata, hello server side!) )); $                         Try { $Message message =NewMessage (); -Bundle bundle =NewBundle (); -Httprequest.setentity (NewUrlencodedformentity (params, HTTP. Utf_8));//Set request parameter entries theHttpClient HttpClient =Newdefaulthttpclient (); -HttpResponse HttpResponse = Httpclient.execute (HttpRequest);//Execution Request return responseWuyi                             if(Httpresponse.getstatusline (). Getstatuscode () = = 200) {//determine if the request is successful the bundle.putstring (msg, entityutils.tostring (Httpresponse.getentity ())); -}Else{ Wu bundle.putstring (msg, not getting the response to the Android server side!) ); -                             } About Message.setdata (bundle); $ handler.sendmessage (message); -}Catch(clientprotocolexception e) { - e.printstacktrace (); -}Catch(unsupportedencodingexception e) { A e.printstacktrace (); +}Catch(IOException e) { the e.printstacktrace (); -                         } $                     } the }). Start (); the             } the         }); the     } -       in     PrivateHandler Handler =NewHandler () { the @Override the          Public voidhandlemessage (Message message) { About             Super. Handlemessage (message); theBundle bundle =Message.getdata (); theString msg =bundle.getstring (msg); the Toast.maketext (Getapplicationcontext (), MSG, Toast.length_long). Show (); +         } -     }; the}</namevaluepair></namevaluepair>

Reference source : 1.


How the Android client interacts with the server-summary

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.