Summary of http basics

1. HTTP protocol (HyperText Transfer Protocol, Hypertext Transfer Protocol) is the most widely used network transmission protocol on the Internet, and all WWW files must comply with this standard.

HTTP is a communication protocol based on TCP/IP to transfer data (HTML files, image files, query results, etc.).

Http communication overview

There are two main ways of Http communication: POST and GET. The former sends data to the server through the Http message entity, which has high security and no limit to the size of data transmission. The latter transmits the parameters to the server through the query string of the URL and displays it in the browser address bar in plain text. It has poor confidentiality and can transmit up to 2048 characters. . But GET requests are not useless - GET requests are mostly used for querying (reading resources) and are efficient. POST requests are used for operations such as registration and login with high security and writing data to the database.

Besides POST and GET, there are other ways of http communication! see http request method

Preparation before coding

Before coding, let's create one Servletthat Servletreceives the client's parameters (name and age) and responds to the client.

@WebServlet(urlPatterns={"/demo.do"})
public class DemoServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        PrintWriter pw = response.getWriter ();
        pw.print( "You use GET to request this servlet.<br />" + "name = " + name + ",age = " + age);
        pw.flush();
        pw.close();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        PrintWriter pw = response.getWriter ();
        pw.print( "You use POST to request this servlet.<br />" + "name = " + name + ",age = " + age);
        pw.flush();
        pw.close();
    }

}

Implement http communication using JDK

URLConnectionImplement a GET request using

  1. instantiate an java.net.URLobject;
  2. Get one through URLthe object's openConnection()methods java.net.URLConnection;
  3. Obtain the input stream through URLConnectionthe method of the object ;getInputStream()
  4. read input stream;
  5. Close the resource.
public void get() throws Exception{

    URL url = new URL("http://127.0.0.1/http/demo.do?name=Jack&age=10");
    URLConnection urlConnection = url.openConnection();                                                     // Open the connection 
    BufferedReader br = new BufferedReader( new InputStreamReader(urlConnection.getInputStream(),"utf-8")); // Get the input stream 
    String line = null ;
    StringBuilder sb = new StringBuilder();
    while ((line = br.readLine()) != null) {
        sb.append(line + "\n");
    }

    System.out.println(sb.toString());
}

 

Running result 1

HttpURLConnectionImplement a POST request using

java.net.HttpURLConnectionYes java.net.URLsubclass, provides more operations on http (getXXX and setXXX methods). A series of HTTP status codes are defined in this class:

http status code

public void post() throws IOException{

    URL url = new URL("http://127.0.0.1/http/demo.do");
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

    httpURLConnection.setDoInput(true);
    httpURLConnection.setDoOutput( true );         // Set the connection to be output 
    httpURLConnection.setRequestMethod("POST"); // Set the request method 
    httpURLConnection.setRequestProperty("charset", "utf-8" );

    PrintWriter pw = new PrintWriter(new BufferedOutputStream(httpURLConnection.getOutputStream()));
    pw.write( "name=welcome");                    // Output data to the connection (equivalent to sending data to the server) 
    pw.write("&age=14" );
    pw.flush();
    pw.close();

    BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"utf-8"));
    String line = null;
    StringBuilder sb = new StringBuilder();
    while ((line = br.readLine()) != null) {    // 读取数据
        sb.append(line + "\n");
    }

    System.out.println(sb.toString());
}

 

Running result 2

use httpclientfor http communication

httpclient greatly simplifies the implementation of http communication in the JDK.

maven dependencies:

<dependency>
    <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.6</version> </dependency> 

GET request

public void httpclientGet() throws Exception{

    // Create HttpClient object 
    HttpClient client = HttpClients.createDefault();

    // Create a GET request (pass the URL string in the constructor) 
    HttpGet get = new HttpGet("http://127.0.0.1/http/demo.do?name=admin&age=40" );

    // Call the execute method of the HttpClient object to get the response 
    HttpResponse response = client.execute(get);

    // Call the getEntity method of the HttpResponse object to get the response entity 
    HttpEntity httpEntity = response.getEntity();

    // Use the EntityUtils tool class to get the string representation of the response 
    String result = EntityUtils.toString(httpEntity,"utf-8" );
    System.out.println(result);
}

 

Running result 3

POST request

public void httpclientPost() throws Exception{

    // Create HttpClient object 
    HttpClient client = HttpClients.createDefault();

    // Create POST request 
    HttpPost post = new HttpPost("http://127.0.0.1/http/demo.do" );

    // Create a List container to store basic key-value pairs (basic key-value pairs are: parameter name - parameter value) 
    List<BasicNameValuePair> parameters = new ArrayList<> ();
    parameters.add(new BasicNameValuePair("name", "张三"));
    parameters.add(new BasicNameValuePair("age", "25"));

    // Add message entity to POST request 
    post.setEntity( new UrlEncodedFormEntity(parameters, "utf-8" ));

    // Get the response and convert it into a string 
    HttpResponse response = client.execute(post);
    HttpEntity httpEntity = response.getEntity();
    String result = EntityUtils.toString(httpEntity,"utf-8");
    System.out.println(result);
}

 

Running result 4

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325489203&siteId=291194637
Recommended