Android Study Notes 20: Http protocol and Java Web Programming

Source: Internet
Author: User

In the course of Android learning, network programming is required in many places. Unfortunately, I have never been familiar with network programming before, but to continue to learn more about Android development, I had to start from and hope to add some knowledge about network programming.

The explanation is very detailed. According to the above installation steps, there should be no problem.

How to Use MyEclipse and Tomcat development tools is also briefly mentioned in the above document. However, let's explore it in practice.

1. Http Protocol Introduction

Http (Hypertext Transfer Protocol) is used to transmit www Data. Based on the client/server model, www consists of a Web browser and a Web server. Http is used to communicate with each other.

Http uses the request/response model. It is based on the TCP/IP protocol and is the application layer protocol between Web browsers and Web servers, is a common, stateless object-oriented protocol.

1.1how HTTP works

How does one establish a connection between a Web browser and a Web server? The procedure is as follows.

Step 1: Obtain the user input content in the browser of the client.

Step 2: After the browser obtains the URL, it will internally send the domain name to the DNS for domain name resolution. After obtaining its IP address, it will be linked to the corresponding server, from the browser to the server port, the TCP/IP protocol is used.

Step 3: Use Socket to implement the TCP/IP protocol.

Step 4: connect the client to the server through port 80.

The specific implementation process of the above four steps is shown in 1. In the Internet, data can be sent and received in three ways: Http, FTP, and TCP/IP.

 

Figure 1 principle of connecting the browser to the server

As shown in figure 1, the content of the client returned by the server has three forms:

(1) return in the form of Html code.

(2) return in the form of an xml string, which is often used in Android development.

(3) return in the form of Json data. From the perspective of network traffic, the Json method is better than the xml method and is easy to parse.

1.2Http Request body

The client sends a request to the server. The request body generally contains the Request Method (post or get), URL, Protocol version, request modifier, message structure similar to MIME of customer information and content, etc.

Content 2 of the Http Request body.

 

Figure 2 Http Request body content

1.3Http response body

The server responds to a client request and uses a status line as the response. The response body contains the Message Protocol version, success or error code, server information, and entity content.

Content 3 of the Http response body.

 

Figure 3 Http response body content

 

2. Java Web instance

After learning about the Http protocol, you can create a simple Java Web instance.

Because it is the first time for Java Web development, although it is a simple instance, I will record every step in the development process in detail, as a memorandum.

2.1 create a project

After running the MyEclipse software, select "File" in the menu bar, select "New", and then select "Web Project". The "New Web Project" dialog box shown in 4 is displayed.

 

Figure 4 New Web Project dialog box

In the "New Web Project" dialog box shown in 4, enter the Project Name, for example, "myhttpnew", in the input box after the Project Name, and then select "Java EE 5.0 ", click "Finish" to complete the creation.

After the project is created, the Resource Directory structure of the project is displayed in the border bar on the left, as shown in Figure 5.

 

Figure 5 Project Resource Directory

2.2 modify the index. jsp file

Double-click to open the index. jsp file. The source code is as follows:

View Code
1 String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/";
2%>
3
4 <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
5 6 7 <base href = "<% = basePath %>">
8
9 <title> My JSP 'index. jsp 'starting page </title>
10 <meta http-equiv = "pragma" content = "no-cache">
11 <meta http-equiv = "cache-control" content = "no-cache">
12 <meta http-equiv = "expires" content = "0">
13 <meta http-equiv = "keywords" content = "keyword1, keyword2, keyword3">
14 <meta http-equiv = "description" content = "This is my page">
15 <! --
16 <link rel = "stylesheet" type = "text/css" href = "styles.css">
17 -->
18 19
20 <body>
21 This is my JSP page. <br>
22 </body>
23 This code is a basic Java Web framework. We can modify it to create a simple Web page. The modified source code is as follows:

View Code
1 <% @ page language = "java" import = "java. util. *" pageEncoding = "UTF-8" %>
2 <%
3 String path = request. getContextPath ();
4%>
5
6 <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
7 8 9
10 <title> test HTTP body content </title>
11 <meta http-equiv = "pragma" content = "no-cache">
12 <meta http-equiv = "cache-control" content = "no-cache">
13 <meta http-equiv = "expires" content = "0">
14 <meta http-equiv = "keywords" content = "keyword1, keyword2, keyword3">
15 <meta http-equiv = "description" content = "This is my page">
16 <! --
17 <link rel = "stylesheet" type = "text/css" href = "styles.css">
18 -->
19 20
21 <body>
22 <form name = "form1" action = "" method = "post">
23 username <input type = "text" name = "username" value = ""/> <br/>
24 key & nbsp; Code <input type = "password" name = "password" value = ""/> <br/>
25 <input type = "submit" name = "submit" value = "submit"/>
26 </form>
27 </body>
28 In the modified Code, the encoding method is "UTF-8" and the webpage title is "test HTTP body content ". The most important thing is to change the content in <body> and add the "username" input box, "password" input box, and a "Submit" button.

Open and run Tomcat, and enter "localhost: 8080/myhttpnew" in the browser. The running effect of the program is 6.

 

Figure 6 webpage preview Effect

In the web page shown in figure 6, we can enter the user name and password and click "Submit". However, the web page does not have any response because the server still lacks operations to respond to client requests, therefore, we need to add some code to complete the server's response to the client's request.

2.3 The server responds to client requests

To facilitate code management, you can create a new package and place the code in the specified package.

Right-click the src directory, select "New", and then select "Package". The "New Java Package" dialog box shown in 7 is displayed.

 

Figure 7 New Java Package dialog box

In the "New Java Package" dialog box shown in Figure 7, enter the Package Name in the input box after the Name, for example, "com. login. manager, and then click "Finish" to create the package. You can see that there is a directory structure "com. login. manager ".

Then, we need to create a Servlet to implement the code of the server responding to the client.

Right-click the "com. login. manager" directory structure, select "New", and then select "Servlet". The "Create a New Servlet" dialog box shown in Figure 8 is displayed.

 

 

Figure 8 Create a New Servlet dialog box

In the "Create a New Servlet" dialog box shown in figure 8, enter the New class Name, such as "LoginAction", in the input box after Name, and the class is inherited from "javax. servlet. http. httpServlet, and then click "Next" to bring up the "Create a New Servlet" dialog box shown in 9.

 

Figure 9 Create a New Servlet Dialog Box 2

Click "Finish" to complete Servlet creation. After the creation is complete. login. add a file "LoginAction. java ", which is the file we created to implement the server response client code.

Open the LoginAction. java file and you can see the source code as follows:

View Code
1 package com. login. manager;
2
3 import java. io. IOException;
4 import java. io. PrintWriter;
5
6 import javax. servlet. ServletException;
7 import javax. servlet. http. HttpServlet;
8 import javax. servlet. http. HttpServletRequest;
9 import javax. servlet. http. HttpServletResponse;
10
11 public class LoginAction extends HttpServlet {
12
13 /**
14 * Constructor of the object.
15 */
16 public LoginAction (){
17 super ();
18}
19
20 /**
21 * Destruction of the servlet. <br>
22 */
23 public void destroy (){
24 super. destroy (); // Just puts "destroy" string in log
25 // Put your code here
26}
27
28 /**
29 * The doGet method of the servlet. <br>
30 *
31 * This method is called when a form has its tag value method equals to get.
32 *
33 * @ param request the request send by the client to the server
34 * @ param response the response send by the server to the client
35 * @ throws ServletException if an error occurred
36 * @ throws IOException if an error occurred
37 */
38 public void doGet (HttpServletRequest request, HttpServletResponse response)
39 throws ServletException, IOException {
40
41 response. setContentType ("text/html ");
42 PrintWriter out = response. getWriter ();
43 out
44. println ("<! Doctype html public \ "-// W3C // dtd html 4.01 Transitional // EN \"> ");
45 out. println ("<HTML> ");
46 out. println ("<HEAD> <TITLE> A Servlet </TITLE> </HEAD> ");
47 out. println ("<BODY> ");
48 out. print ("This is ");
49 out. print (this. getClass ());
50 out. println (", using the GET method ");
51 out. println ("</BODY> ");
52 out. println ("</HTML> ");
53 out. flush ();
54 out. close ();
55}
56
57 /**
58 * The doPost method of the servlet. <br>
59 *
60 * This method is called when a form has its tag value method equals to post.
61 *
62 * @ param request the request send by the client to the server
63 * @ param response the response send by the server to the client
64 * @ throws ServletException if an error occurred
65 * @ throws IOException if an error occurred
66 */
67 public void doPost (HttpServletRequest request, HttpServletResponse response)
68 throws ServletException, IOException {
69
70 response. setContentType ("text/html ");
71 PrintWriter out = response. getWriter ();
72 out
73. println ("<! Doctype html public \ "-// W3C // dtd html 4.01 Transitional // EN \"> ");
74 out. println ("<HTML> ");
75 out. println ("<HEAD> <TITLE> A Servlet </TITLE> </HEAD> ");
76 out. println ("<BODY> ");
77 out. print ("This is ");
78 out. print (this. getClass ());
79 out. println (", using the POST method ");
80 out. println ("</BODY> ");
81 out. println ("</HTML> ");
82 out. flush ();
83 out. close ();
84}
85
86 /**
87 * Initialization of the servlet. <br>
88 *
89 * @ throws ServletException if an error occurs
90 */
91 public void init () throws ServletException {
92 // Put your code here
93}
94
95}
Here, we only need to modify the doPost () method. The source code of the modified doPost () method is as follows:

View Code
1 /**
2 * The doPost method of the servlet. <br>
3 *
4 * This method is called when a form has its tag value method equals to post.
5 *
6 * @ param request the request send by the client to the server
7 * @ param response the response send by the server to the client
8 * @ throws ServletException if an error occurred
9 * @ throws IOException if an error occurred
10 */
11 public void doPost (HttpServletRequest request, HttpServletResponse response)
12 throws ServletException, IOException {
13
14 response. setContentType ("text/html ");
15 PrintWriter out = response. getWriter ();
16
17 String username = request. getParameter ("username ");
18 String password = request. getParameter ("password ");
19
20 if (username. equals ("admin") & password. equals ("123 ")){
21 // indicates the result returned by the server
22 out. print ("login is success! ");
23} else {
24 out. print ("incorrect user name or password! ");
25}
26
27 out. flush ();
28 out. close ();
29}
In addition, we also need to modify the index. action = "" For action = "<% = path %>/servlet/LoginAction" in the <form> label under the <body> label in the jsp file ", specifies the response execution path.

Restart Tomcat and enter the username "admin" and password "123" on the page shown in Figure 6. Then, click "Submit" to view the server responding to the client request, the corresponding response message "login is success!" is provided! ", 10.

 

Figure 10 Server Response Results

So far, we have completed a simple Java Web instance.

 

Related Article

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.