Android client and website data interaction implementation (Http-based Data Acquisition Method)
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:
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>
Struts2
Org. apache. struts2.dispatcher. FilterDispatcher
Struts2
/*
Index. jsp
Then write the struts. xml file and put it in the WebRoot/WEB-INF/lib directory: the following code:
"-// Apache Software Foundation // DTD Struts Configuration 2.0 // EN"
Http://struts.apache.org/dtds/struts-2.0.dtd>
After the configuration is complete, we can write the action based on the 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. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + CjxzdHJvbmc + v827p7bLo7o8L3N0cm9uZz48L3A + fingerprint + dPasb612LXEd2Viz + fingerprint "http://www.bkjia.com/uploads/allimg/140803/0415345363-1.gif" alt = "Copy code">
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 ();
}
}
========================================================== ========================================================== ========================================================== ============