Android client and website data interaction implementation (Http-based data acquisition method), android Client

Source: Internet
Author: User
Tags i18n

Android client and website data interaction implementation (Http-based data acquisition method), android Client

Android clients generally do not directly access the website database, but send get or post requests like a browser, and then the website returns the data format that the client can understand. The client parses the data and displays it on the interface, common data formats are xml and json.

It can be understood that the client is actually a browser with your own markup language defined. Generally, the browser can parse html + css data, the android client can parse xml and json (or not, but the Mars format defined by yourself). In order to meet the requirements of the client to output this data format, you have to develop different interfaces for browser access for the client.

To develop a website client, you need:

1. When a get or post request is simulated on the client, the request is finally sent as a url through the http protocol.

2. parse the data returned by the server on the client ticket

3. generate corresponding json data on the server based on the request (we strongly recommend that you use json instead of xml. json with the same character can return more useful data and facilitate resolution)

The HttpURLConnection class of java can implement get and post, but it is very troublesome. We still use the HttpClient open source code to implement it.


I have summarized two ways for android to interact with the server.

1. http protocol (we generally use the HttpClient open-source project) to obtain data based on Http protocol.

The server-side technology we adopt is java, the framework is Struts2, or Servlet, or data can be obtained directly from the JSP page.

Then, let's start this journey:

First of all: Compile the server method. The MVC framework I use here is Struts2. The purpose is very simple. It is to create a complete commercial project in the future. The technical configuration is android + SSH. Of course, the length is limited. I will use Strtus2 directly here.

Server:

To add Struts2 support to the project, we must import some Struts2 class libraries as follows (some jar packages are not required, but we may need to use the extension later, ):

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 to process JSON format data to use

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

The above jar package needs to be placed in the WebRoot/WEB-INF/lib directory

In the web. xml file, click:

<? 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/javaee
Http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd>


<! -- Define the core controller of Struts2: FilterDispatcher -->
<Filter>
<! -- Define the name of the core Filter -->
<Filter-name> struts2 </filter-name>
<! -- Define the implementation class of Filter -->
<Filter-class> org. apache. struts2.dispatcher. FilterDispatcher </filter-class>
</Filter>

<Filter-mapping>
<Filter-name> struts2 </filter-name>
<Url-pattern>/* </url-pattern>
</Filter-mapping>

<Welcome-file-list>
<Welcome-file> index. jsp </welcome-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"> <! -- Modify struts-default to json-default -->
<! -- Setting action -->
<Action name = "login" class = "com. dongzi. action. loginAction" method = "login">
<Result type = "json"> </result> <! -- The return value type is set to json, And the return page is not set -->
</Action>
</Package>
</Struts>

After the configuration is complete, we can write the action according to the <action> tag content. The method is the login corresponding to the method, and the class name is loginAction,

Note: The package inherits the json-default type and the output result type is json.

As follows:
Public class loginAction extends ActionSupport implements
ServletRequestAware, ServletResponseAware {
/**
*
*/
Private static final long serialVersionUID = 1L;

HttpServletRequest request;
HttpServletResponse response;

Public void setServletRequest (HttpServletRequest request ){
This. request = request;
}

Public void setServletResponse (HttpServletResponse response ){
This. response = response;
}

Public void login (){
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 strange, Japanese! ");
} Else if (this. request. getParameter ("username"). equals ("zhd ")){
This. response. getWriter (). write ("no error, I am Dongzi! ");
} Else {
This. response. getWriter (). write ("I am Dongzi! ");
}

// Json processing of the object to be returned
// JSONObject json = JSONObject. fromObject (this. getUsername ());
// Output format: {"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;
}
}

Run the following command: http: // localhost: 8080/PDAServer/login. action? Username = 123456 of course you can enter the URL of other parameters

Run successfully.

Client:

Note that the simulator regards itself as localhost and 127.0.0.1. Therefore, if the local web project is used for testing, you must change the IP address to 10.0.2.2.

Public class MainActivity extends Activity {
/** Called when the activity is first created .*/
// The simulator regards itself as localhost, and the server should be 10.0.2.2
Private static String url = "http://10.0.2.2: 8080/PDAServer/login. action ";
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
GetPDAServerData (url );
}

/**
* Request service
* @ Param url
*/
Private void getPDAServerData (String url ){
Url + = "? Username = 123456 "; HttpClient client = new DefaultHttpClient ();
HttpPost request;
Try {
Request = new HttpPost (new URI (url ));
HttpResponse response=client.exe cute (request );
// Determine whether the request is successful
If (response. getStatusLine (). getStatusCode () = 200 ){
HttpEntity entity = response. getEntity ();
If (entity! = Null ){
String out = EntityUtils. toString (entity );
New AlertDialog. Builder (this). setMessage (out). create (). show ();
}
}

} Catch (URISyntaxException e ){
E. printStackTrace ();
}
Catch (ClientProtocolException e ){
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
========================================================== ========================================================== ========================================================== ============

Android development and background data interaction

If the background Http can use HttpClient to submit the simulated get/post

Want to learn about Data Interaction Between the android client and the server? For example, how to log on? How to read data from the server and display it on the client

Sign-1 integer. The highest digit is 1, indicating a negative number, but the stored computer? In the form of supplement-1 The actual storage format is 11111111. If your client reads and saves the unsigned integer, of course, 255 of the Code is a simple return value check, best server and client byte stream reading and writing. Hope to help you. Thank you for choosing

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.