On the Differences among HttpClient okhttp and RestTemplate

  • 2021-09-20 20:43:40
  • OfStack

1. HttpClient

1. pom Dependence


<!--HttpClient-->
<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>

2. Implementation of HttpClient code


public class HttpClientUtil {
    /**
     * httpClient Adj. get Request mode 
     *  Use GetMethod To access 1 A URL Corresponding web page implementation steps: 
     * 1. Generate 1 A HttpClient Object and set corresponding parameters; 
     * 2. Generate 1 A GetMethod Object and set the parameters of the response; 
     * 3. Use HttpClient To execute the generated object GetMethod Generated Get Methods; 
     * 4. Processing the response status code; 
     * 5. If the response is normal, handle HTTP Response content; 
     * 6. Release the connection. 
     * @param url
     * @param charset
     * @return
     */
    public static String doGet(String url, String charset) {
        //1. Generate HttpClient Object and set the parameters 
        HttpClient httpClient = new HttpClient();
        // Settings Http Connection timeout is 5 Seconds 
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        //2. Generate GetMethod Object and set the parameters 
        GetMethod getMethod = new GetMethod(url);
        // Settings get Request timeout is 5 Seconds 
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        // Set the request retry processing, using the default retry processing: request 3 Times 
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        String response = "";
        //3. Execute HTTP GET  Request 
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            //4. Determine the status code of access 
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println(" Error in request: " + getMethod.getStatusLine());
            }
            //5. Deal with HTTP Response content 
            //HTTP In response to the header information, simply print it here 
            Header[] headers = getMethod.getResponseHeaders();
            for(Header h : headers) {
                System.out.println(h.getName() + "---------------" + h.getValue());
            }
            // Read HTTP In response to content, simply print the web page content here 
            // Read as a byte array 
            byte[] responseBody = getMethod.getResponseBody();
            response = new String(responseBody, charset);
            System.out.println("-----------response:" + response);
            // Read as InputStream It is recommended to use when there is a large amount of web content data 
            //InputStream response = getMethod.getResponseBodyAsStream();
        } catch (HttpException e) {
            // A fatal exception occurred, possibly because the protocol was wrong or there was something wrong with the returned content 
            System.out.println(" Please check the entered URL!");
            e.printStackTrace();
        } catch (IOException e) {
            // A network exception occurred 
            System.out.println(" A network exception occurred !");
        } finally {
            //6. Release connection 
            getMethod.releaseConnection();
        }
        return response;
    }
    /**
     * post Request 
     * @param url
     * @param json
     * @return
     */
    public static String doPost(String url, JSONObject json){
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        postMethod.addRequestHeader("accept", "*/*");
        postMethod.addRequestHeader("connection", "Keep-Alive");
        // Settings json Format transfer 
        postMethod.addRequestHeader("Content-Type", "application/json;charset=GBK");
        // You must set the following Header
        postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        // Add request parameters 
        postMethod.addParameter("commentId", json.getString("commentId"));
        String res = "";
        try {
            int code = httpClient.executeMethod(postMethod);
            if (code == 200){
                res = postMethod.getResponseBodyAsString();
                System.out.println(res);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }
    public static void main(String[] args) {
        System.out.println(doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "GBK"));
        System.out.println("----------- Partition line ------------");
        System.out.println("----------- Partition line ------------");
        System.out.println("----------- Partition line ------------");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("commentId", "13026194071");
        System.out.println(doPost("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", jsonObject));
    }
}

3. Recommendations

The code is complicated, and you have to worry about resource recovery. The code is very complex and redundant, so it is not recommended to use it directly.

2. okhttp

1. Introduction

OkHttp is an efficient HTTP client that allows all requests with the same host address to share the same socket connection; Connection pooling reduces request delay; Transparent GZIP compression reduces the size of response data; Cache response content to avoid 1 completely duplicate request

When there is a network problem, OkHttp still sticks to its duty, and it will automatically recover the connection problem like 1. If your service has multiple IP addresses, when the first IP request fails, OkHttp will alternately try other IP configured by you. OkHttp uses modern TLS technology (SNI, ALPN) to initialize a new connection, and will retreat to TLS 1.0 when handshake fails.

2. pom Dependence


<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.10.0</version>
</dependency>

Its request/response API is designed using the constructor pattern builders and supports blocking synchronous requests and callback asynchronous requests.

3. Configuration file


@Configuration
public class OkHttpConfig {
    @Bean
    public OkHttpClient okHttpClient() {
        return new OkHttpClient.Builder()
                //.sslSocketFactory(sslSocketFactory(), x509TrustManager())
                .retryOnConnectionFailure(false)
                .connectionPool(pool())
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30,TimeUnit.SECONDS)
                .build();
    }
    @Bean
    public X509TrustManager x509TrustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }
            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
    }
    @Bean
    public SSLSocketFactory sslSocketFactory() {
        try {
            // Trust any link 
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * Create a new connection pool with tuning parameters appropriate for a single-user application.
     * The tuning parameters in this pool are subject to change in future OkHttp releases. Currently
     */
    @Bean
    public ConnectionPool pool() {
        return new ConnectionPool(200, 5, TimeUnit.MINUTES);
    }
}

4. Client Tools


@Slf4j
public class OkHttpClient {
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private volatile static okhttp3.OkHttpClient client;
    private static final int MAX_IDLE_CONNECTION = Integer
            .parseInt(ConfigManager.get("httpclient.max_idle_connection"));
    private static final long KEEP_ALIVE_DURATION = Long
            .parseLong(ConfigManager.get("httpclient.keep_alive_duration"));
    private static final long CONNECT_TIMEOUT = Long.parseLong(ConfigManager.get("httpclient.connectTimeout"));
    private static final long READ_TIMEOUT = Long.parseLong(ConfigManager.get("httpclient. "));
    /**
     *  Singleton pattern ( Double check mode )  Getting class instances  
     *
     * @return client
     */
    private static okhttp3.OkHttpClient getInstance() {
        if (client == null) {
            synchronized (okhttp3.OkHttpClient.class) {
                if (client == null) {
                    client = new okhttp3.OkHttpClient.Builder()
                            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                            .connectionPool(new ConnectionPool(MAX_IDLE_CONNECTION, KEEP_ALIVE_DURATION,
                                    TimeUnit.MINUTES))
                            .build();
                }
            }
        }
        return client;
    }
    public static String syncPost(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try {
            Response response = OkHttpClient.getInstance().newCall(request).execute();
            if (response.isSuccessful()) {
                String result = response.body().string();
                log.info("syncPost response = {}, responseBody= {}", response, result);
                return result;
            }
            String result = response.body().string();
            log.info("syncPost response = {}, responseBody= {}", response, result);
            throw new IOException("3 The square interface returns http The status code is " + response.code());
        } catch (Exception e) {
            log.error("syncPost() url:{} have a ecxeption {}", url, e);
            throw new RuntimeException("syncPost() have a ecxeption {}" + e.getMessage());
        }
    }
    public static String syncGet(String url, Map<String, Object> headParamsMap) throws IOException {
        Request request;
        final Request.Builder builder = new Request.Builder().url(url);
        try {
            if (!CollectionUtils.isEmpty(headParamsMap)) {
                final Iterator<Map.Entry<String, Object>> iterator = headParamsMap.entrySet()
                        .iterator();
                while (iterator.hasNext()) {
                    final Map.Entry<String, Object> entry = iterator.next();
                    builder.addHeader(entry.getKey(), (String) entry.getValue());
                }
            }
            request = builder.build();
            Response response = OkHttpClient.getInstance().newCall(request).execute();
            String result = response.body().string();
            log.info("syncGet response = {},responseBody= {}", response, result);
            if (!response.isSuccessful()) {
                throw new IOException("3 The square interface returns http The status code is " + response.code());
            }
            return result;
        } catch (Exception e) {
            log.error("remote interface url:{} have a ecxeption {}", url, e);
            throw new RuntimeException("3 The square interface returned an exception ");
        }
    }
}

3. RestTemplate

1. pom Dependence


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

2. get request (cancel the parameters without parameters)


// 1-getForObject()
User user1 = this.restTemplate.getForObject(uri, User.class);
// 2-getForEntity()
ResponseEntity<User> responseEntity1 = this.restTemplate.getForEntity(uri, User.class);
HttpStatus statusCode = responseEntity1.getStatusCode();
HttpHeaders header = responseEntity1.getHeaders();
User user2 = responseEntity1.getBody();
  
// 3-exchange()
RequestEntity requestEntity = RequestEntity.get(new URI(uri)).build();
ResponseEntity<User> responseEntity2 = this.restTemplate.exchange(requestEntity, User.class);
User user3 = responseEntity2.getBody();

Mode 1:


Notice notice = restTemplate.getForObject("http://fantj.top/notice/list/{1}/{2}"
                , Notice.class,1,5);

Mode 2:


Map<String,String> map = new HashMap();
map.put("start","1");
map.put("page","5");
Notice notice = restTemplate.getForObject("http://fantj.top/notice/list/"
        , Notice.class,map);

3. post Request


// 1-postForObject()
User user1 = this.restTemplate.postForObject(uri, user, User.class);
// 2-postForEntity()
ResponseEntity<User> responseEntity1 = this.restTemplate.postForEntity(uri, user, User.class);
// 3-exchange()
RequestEntity<User> requestEntity = RequestEntity.post(new URI(uri)).body(user);
ResponseEntity<User> responseEntity2 = this.restTemplate.exchange(requestEntity, User.class);

Mode 1:


public class HttpClientUtil {
    /**
     * httpClient Adj. get Request mode 
     *  Use GetMethod To access 1 A URL Corresponding web page implementation steps: 
     * 1. Generate 1 A HttpClient Object and set corresponding parameters; 
     * 2. Generate 1 A GetMethod Object and set the parameters of the response; 
     * 3. Use HttpClient To execute the generated object GetMethod Generated Get Methods; 
     * 4. Processing the response status code; 
     * 5. If the response is normal, handle HTTP Response content; 
     * 6. Release the connection. 
     * @param url
     * @param charset
     * @return
     */
    public static String doGet(String url, String charset) {
        //1. Generate HttpClient Object and set the parameters 
        HttpClient httpClient = new HttpClient();
        // Settings Http Connection timeout is 5 Seconds 
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        //2. Generate GetMethod Object and set the parameters 
        GetMethod getMethod = new GetMethod(url);
        // Settings get Request timeout is 5 Seconds 
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        // Set the request retry processing, using the default retry processing: request 3 Times 
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        String response = "";
        //3. Execute HTTP GET  Request 
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            //4. Determine the status code of access 
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println(" Error in request: " + getMethod.getStatusLine());
            }
            //5. Deal with HTTP Response content 
            //HTTP In response to the header information, simply print it here 
            Header[] headers = getMethod.getResponseHeaders();
            for(Header h : headers) {
                System.out.println(h.getName() + "---------------" + h.getValue());
            }
            // Read HTTP In response to content, simply print the web page content here 
            // Read as a byte array 
            byte[] responseBody = getMethod.getResponseBody();
            response = new String(responseBody, charset);
            System.out.println("-----------response:" + response);
            // Read as InputStream It is recommended to use when there is a large amount of web content data 
            //InputStream response = getMethod.getResponseBodyAsStream();
        } catch (HttpException e) {
            // A fatal exception occurred, possibly because the protocol was wrong or there was something wrong with the returned content 
            System.out.println(" Please check the entered URL!");
            e.printStackTrace();
        } catch (IOException e) {
            // A network exception occurred 
            System.out.println(" A network exception occurred !");
        } finally {
            //6. Release connection 
            getMethod.releaseConnection();
        }
        return response;
    }
    /**
     * post Request 
     * @param url
     * @param json
     * @return
     */
    public static String doPost(String url, JSONObject json){
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        postMethod.addRequestHeader("accept", "*/*");
        postMethod.addRequestHeader("connection", "Keep-Alive");
        // Settings json Format transfer 
        postMethod.addRequestHeader("Content-Type", "application/json;charset=GBK");
        // You must set the following Header
        postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        // Add request parameters 
        postMethod.addParameter("commentId", json.getString("commentId"));
        String res = "";
        try {
            int code = httpClient.executeMethod(postMethod);
            if (code == 200){
                res = postMethod.getResponseBodyAsString();
                System.out.println(res);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }
    public static void main(String[] args) {
        System.out.println(doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "GBK"));
        System.out.println("----------- Partition line ------------");
        System.out.println("----------- Partition line ------------");
        System.out.println("----------- Partition line ------------");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("commentId", "13026194071");
        System.out.println(doPost("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", jsonObject));
    }
}
0

Mode 2:


public class HttpClientUtil {
    /**
     * httpClient Adj. get Request mode 
     *  Use GetMethod To access 1 A URL Corresponding web page implementation steps: 
     * 1. Generate 1 A HttpClient Object and set corresponding parameters; 
     * 2. Generate 1 A GetMethod Object and set the parameters of the response; 
     * 3. Use HttpClient To execute the generated object GetMethod Generated Get Methods; 
     * 4. Processing the response status code; 
     * 5. If the response is normal, handle HTTP Response content; 
     * 6. Release the connection. 
     * @param url
     * @param charset
     * @return
     */
    public static String doGet(String url, String charset) {
        //1. Generate HttpClient Object and set the parameters 
        HttpClient httpClient = new HttpClient();
        // Settings Http Connection timeout is 5 Seconds 
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        //2. Generate GetMethod Object and set the parameters 
        GetMethod getMethod = new GetMethod(url);
        // Settings get Request timeout is 5 Seconds 
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        // Set the request retry processing, using the default retry processing: request 3 Times 
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        String response = "";
        //3. Execute HTTP GET  Request 
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            //4. Determine the status code of access 
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println(" Error in request: " + getMethod.getStatusLine());
            }
            //5. Deal with HTTP Response content 
            //HTTP In response to the header information, simply print it here 
            Header[] headers = getMethod.getResponseHeaders();
            for(Header h : headers) {
                System.out.println(h.getName() + "---------------" + h.getValue());
            }
            // Read HTTP In response to content, simply print the web page content here 
            // Read as a byte array 
            byte[] responseBody = getMethod.getResponseBody();
            response = new String(responseBody, charset);
            System.out.println("-----------response:" + response);
            // Read as InputStream It is recommended to use when there is a large amount of web content data 
            //InputStream response = getMethod.getResponseBodyAsStream();
        } catch (HttpException e) {
            // A fatal exception occurred, possibly because the protocol was wrong or there was something wrong with the returned content 
            System.out.println(" Please check the entered URL!");
            e.printStackTrace();
        } catch (IOException e) {
            // A network exception occurred 
            System.out.println(" A network exception occurred !");
        } finally {
            //6. Release connection 
            getMethod.releaseConnection();
        }
        return response;
    }
    /**
     * post Request 
     * @param url
     * @param json
     * @return
     */
    public static String doPost(String url, JSONObject json){
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        postMethod.addRequestHeader("accept", "*/*");
        postMethod.addRequestHeader("connection", "Keep-Alive");
        // Settings json Format transfer 
        postMethod.addRequestHeader("Content-Type", "application/json;charset=GBK");
        // You must set the following Header
        postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        // Add request parameters 
        postMethod.addParameter("commentId", json.getString("commentId"));
        String res = "";
        try {
            int code = httpClient.executeMethod(postMethod);
            if (code == 200){
                res = postMethod.getResponseBodyAsString();
                System.out.println(res);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }
    public static void main(String[] args) {
        System.out.println(doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "GBK"));
        System.out.println("----------- Partition line ------------");
        System.out.println("----------- Partition line ------------");
        System.out.println("----------- Partition line ------------");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("commentId", "13026194071");
        System.out.println(doPost("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", jsonObject));
    }
}
1

Attention should be paid to using RestTemplate:

Use RestTemplate to send a request. When the request body is String, it should be configured as follows:


public class HttpClientUtil {
    /**
     * httpClient Adj. get Request mode 
     *  Use GetMethod To access 1 A URL Corresponding web page implementation steps: 
     * 1. Generate 1 A HttpClient Object and set corresponding parameters; 
     * 2. Generate 1 A GetMethod Object and set the parameters of the response; 
     * 3. Use HttpClient To execute the generated object GetMethod Generated Get Methods; 
     * 4. Processing the response status code; 
     * 5. If the response is normal, handle HTTP Response content; 
     * 6. Release the connection. 
     * @param url
     * @param charset
     * @return
     */
    public static String doGet(String url, String charset) {
        //1. Generate HttpClient Object and set the parameters 
        HttpClient httpClient = new HttpClient();
        // Settings Http Connection timeout is 5 Seconds 
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        //2. Generate GetMethod Object and set the parameters 
        GetMethod getMethod = new GetMethod(url);
        // Settings get Request timeout is 5 Seconds 
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        // Set the request retry processing, using the default retry processing: request 3 Times 
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        String response = "";
        //3. Execute HTTP GET  Request 
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            //4. Determine the status code of access 
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println(" Error in request: " + getMethod.getStatusLine());
            }
            //5. Deal with HTTP Response content 
            //HTTP In response to the header information, simply print it here 
            Header[] headers = getMethod.getResponseHeaders();
            for(Header h : headers) {
                System.out.println(h.getName() + "---------------" + h.getValue());
            }
            // Read HTTP In response to content, simply print the web page content here 
            // Read as a byte array 
            byte[] responseBody = getMethod.getResponseBody();
            response = new String(responseBody, charset);
            System.out.println("-----------response:" + response);
            // Read as InputStream It is recommended to use when there is a large amount of web content data 
            //InputStream response = getMethod.getResponseBodyAsStream();
        } catch (HttpException e) {
            // A fatal exception occurred, possibly because the protocol was wrong or there was something wrong with the returned content 
            System.out.println(" Please check the entered URL!");
            e.printStackTrace();
        } catch (IOException e) {
            // A network exception occurred 
            System.out.println(" A network exception occurred !");
        } finally {
            //6. Release connection 
            getMethod.releaseConnection();
        }
        return response;
    }
    /**
     * post Request 
     * @param url
     * @param json
     * @return
     */
    public static String doPost(String url, JSONObject json){
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        postMethod.addRequestHeader("accept", "*/*");
        postMethod.addRequestHeader("connection", "Keep-Alive");
        // Settings json Format transfer 
        postMethod.addRequestHeader("Content-Type", "application/json;charset=GBK");
        // You must set the following Header
        postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        // Add request parameters 
        postMethod.addParameter("commentId", json.getString("commentId"));
        String res = "";
        try {
            int code = httpClient.executeMethod(postMethod);
            if (code == 200){
                res = postMethod.getResponseBodyAsString();
                System.out.println(res);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }
    public static void main(String[] args) {
        System.out.println(doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "GBK"));
        System.out.println("----------- Partition line ------------");
        System.out.println("----------- Partition line ------------");
        System.out.println("----------- Partition line ------------");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("commentId", "13026194071");
        System.out.println(doPost("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", jsonObject));
    }
}
2

If there is no custom StringHttpMessageConverter, the default character set used by StringHttpMessageConverter is ISO_8859_1. When the request body contains Chinese, it will be garbled.


Related articles: