The difference between POST/GET requests and Java's implementation of HTTP (post/get) requests

The difference between POST/GET requests and Java's implementation of HTTP (post/get) requests

The difference between POST and GET requests

1. Definition of get and post

HTTP requests are in pairs, and if there is a request, there will be a response. Call them "upstream request" and "downstream response". No matter what kind of request, the data will be transmitted in the form of "header" + "message";

get and post requests are two request methods in the http protocol;

Get is generally used to obtain server information, and post is generally used to update information.

2. Difference

  • GET parameters are passed through the URL, and POST is placed in the Request body.

    • The data of the get request will be appended to the URL (that is, the data is placed in the HTTP protocol header) to separate the URL and the transmission data, and the parameters are connected by &
    • If the data is an English letter/number, send it as it is, if it is a space, convert it to +, if it is a Chinese/other character, directly encrypt the string with BASE64, such as: %E4%BD%A0%E5%A5% BD, where XX in %XX is the ASCII representation of the symbol in hexadecimal.
  • GET is harmless when the browser falls back, while POST submits the request again.

  • The URL address generated by GET can be Bookmarked, but not POST.

  • GET requests will be actively cached by the browser, but POST will not, unless manually set.

  • GET requests can only be url encoded (application/x-www-form-urlencoded), while POST supports multiple encoding methods (application/x-www-form-urlencoded or multipart/form-data. Use multiple encodings for binary data) .

  • GET request parameters will be completely retained in the browser history, while parameters in POST will not be retained.

  • The parameters transmitted in the URL of the GET request have a length limit, but the POST does not.

    • The data in the url submitted by the get request can only be up to 1024 bytes. This limit is added by the browser or server. The http protocol does not limit the length of the url. The purpose is to ensure that the server and browser can run normally and prevent Someone maliciously sent the request.
        There is no size limit for post requests.
  • For the data type of parameters, GET only accepts ASCII characters, while POST has no restrictions.

  • GET is less secure than POST because the parameters are exposed directly on the URL, so they cannot be used to pass sensitive information.

  • GET generates one TCP packet; POST generates two TCP packets.

  • The get method needs to use Request.QueryString to obtain the value of the variable, and the post method uses Request.Form to obtain the value of the variable.

  • (Most) browsers usually limit the url length to 2K bytes, while (most) servers handle urls up to 64K in size. GET and POST are essentially TCP connections, there is no difference. However, due to HTTP regulations and browser/server limitations, they show some differences in the application process. For GET requests, the browser will send the http header and data together, and the server will respond with 200 (return data); for POST, the browser will send the header first, the server will respond with 100 continue, the browser will send data, and the server will respond 200 ok (return data). Because POST requires two steps and consumes a little more time, it seems that GET is more efficient than POST. Therefore, the Yahoo team recommends replacing POST with GET to optimize website performance, but be cautious.

    • Both GET and POST have their own semantics and cannot be mixed casually.
    • According to research, when the network environment is good, the difference between the time to send a packet and the time to send two packets can basically be ignored. In the case of a poor network environment, TCP with two packets has a great advantage in verifying the integrity of the data packet.
    • Not all browsers send the packet twice in the POST, Firefox only sends it once.

Implement HTTP requests based on the SpringBoot framework

1. Introduce SpringBoot dependency

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.2.13.RELEASE</version>
        </dependency>

2. HttpRestUtils request tool class

package com.javanoteany.httprest.util;

import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;


public class HttpRestUtils {
    
    

    /**
     * post
     * @param url 访问路径
     * @param params 参数
     * @return 返回响应体
     * @throws IOException
     */

    public static String post(String url, MultiValueMap<String, String> params) throws IOException {
    
    
        return  httpRestClient(url, HttpMethod.POST, params);
    }

    /**
     * get
     * @param url 访问路径
     * @param params 参数
     * @return 返回响应体
     * @throws IOException
     */
    public static String get(String url, MultiValueMap<String, String> params) throws IOException {
    
    
        return  httpRestClient(url, HttpMethod.GET, params);
    }

    /**
     * HttpMethod  post/get
     * */
    private static String httpRestClient(String url, HttpMethod method, MultiValueMap<String, String> params) throws IOException {
    
    
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(10*1000); //设置连接超时时间
        requestFactory.setReadTimeout(10*1000); //设置读取超时时间
        RestTemplate client = new RestTemplate(requestFactory);
        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        /**
         * public static final MediaType APPLICATION_ATOM_XML = new MediaType("application", "atom+xml");
         * public static final MediaType APPLICATION_CBOR = new MediaType("application", "cbor");
         * public static final MediaType APPLICATION_FORM_URLENCODED = new MediaType("application", "x-www-form-urlencoded");
         * public static final MediaType APPLICATION_JSON = new MediaType("application", "json");
         */
        headers.setContentType(MediaType.APPLICATION_JSON); //json格式,可以切换成其他数据传输格式
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
        //  执行HTTP请求
        ResponseEntity<String> response = null;
        try{
    
    
            response = client.exchange(url, method, requestEntity, String.class);
            return response.getBody();
        }
        catch (HttpClientErrorException e){
    
    
            System.out.println("HttpClientErrorException" + e.getMessage());
            System.out.println(e.getStatusText());
            System.out.println(e.getResponseBodyAsString());
            e.printStackTrace();
            return "";
        }
        catch (Exception e) {
    
    
            System.out.println("Exception" + e.getMessage());
            e.printStackTrace();
            return "";
        }
    }
}

3. Use of tools

package com.javanoteany.httprest;

import com.javanoteany.httprest.util.HttpRestUtils;
import org.springframework.http.HttpMethod;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

public class HttpRestMain {
    
    

    public static String httpPost() {
    
    
        try {
    
    
            //api url地址
            String url = "http://127.0.0.1:8200/commit/getCommitList";
            // 封装参数,使用多值Map(一个key允许对应多个value)
            MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
            params.add("projectName", "117");
            params.add("number", "1");
            System.out.print("发送数据:" + params.toString());
            //发送http请求并返回结果
            String result = HttpRestUtils.post(url, params);
            System.out.print("接收反馈:" + result);
            return result;
        } catch (Exception e) {
    
    
            System.out.println("httpPost发生异常" + e.getMessage());
            return "";
        }
    }

    public static String httpGet() {
    
    
        try {
    
    
            //api url地址
            String url = "http://127.0.0.1:8200/commit/getCommitList";
            // 封装参数,使用多值Map(一个key允许对应多个value)
            MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
            params.add("projectName", "117");
            params.add("number", "1");
            System.out.print("发送数据:" + params.toString());
            //发送http请求并返回结果
            String result = HttpRestUtils.get(url, params);
            System.out.print("接收反馈:" + result);
            return result;
        } catch (Exception e) {
    
    
            System.out.println("httpGet发生异常" + e.getMessage());
            return "";
        }
    }

    public static void main(String[] args) {
    
    
        String s = httpPost();
        String s1 = httpGet();
        System.out.println(s);
        System.out.println(s1);
    }
}

Guess you like

Origin blog.csdn.net/zzj_csdn/article/details/127372326
Recommended