欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

RestTemplate发送POST请求

程序员文章站 2022-06-24 22:26:50
...

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.Collections;

public class RestTemplateUtil {

    @Value("${url}")
    private String url;

    @Autowired
    private RestTemplate restTemplate;

    @Bean
    public RestTemplate restTemplate(){
        RestTemplate template = new RestTemplate();
        // messageConverters是RestTemplate的一个final修饰的List类型的成员变量
        // messageConverters的第二个元素存储的是StringHttpMessageConverter类型的消息转换器
        // StringHttpMessageConverter的默认字符集是ISO-8859-1,在此处设置utf-8字符集避免产生乱码
        template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return template;
    }

    public String sendMessage(String jsonParam,String endUrl){
        // 自定义请求头
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(type);
        headers.setAcceptCharset(Collections.singletonList(Charset.forName("UTF-8")));
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));
        // 参数
        HttpEntity<String> entity = new HttpEntity<String>(jsonParam, headers);
        // POST方式请求
        ResponseEntity<String> responseEntity = restTemplate.exchange(url+endUrl, HttpMethod.POST, entity, String.class);
        if(responseEntity == null){
            return null;
        }
        return responseEntity.getBody().toString();
    }

}

相关标签: 1 post spring