Recently used RestTemplate send out post request , A lot of problems , Such as conversion httpMessage fail , Chinese random code, etc , It took a long time to find the following easier way :

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        
        JSONObject jsonObj = JSONObject.fromObject(params);
        
        HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);

        String result = restTemplate.postForObject(url, formEntity, String.class);

as Fruit is directly used in postForObject It's easy to pass in objects in no suitable HttpMessageConverter found for request type Error of , It is recommended to convert to string directly , see jsonObj.otString(), Someone on the Internet said that setting RestTemplate Of HttpMessageConverter, Try to introduce all kinds of bags . In addition, we should pay attention to the problem of Chinese coding , Someone on the Internet said StringHttpMessageConverter Default use ISO-8859-1, To specify as UTF-8 code , I didn't succeed in my attempt , Finally, by specifying contentType It's solved .