0%

RestTemplate 发送post请求

SpringBoot使用RestTemplate发送POST请求的参数有application/jsonFormData两种形式:

  1. 参数是json形式,直接使用阿里巴巴的json包 com.alibaba.fastjson ,代码如下:

    1
    2
    3
    4
    5
    url='http://posturl';
    JSONObject postData = new JSONObject();
    postData.put("id", 1);
    JSONObject result = restTemplate.postForEntity(url, postData, JSONObject.class).getBody();
    return result;
  2. 参数是formdata形式则需要使用RestTemplate发送multipart/form-data格式的数据

  • 对请求头进行设置

    1
    2
    3
    4
    5
    6
    7
    String url = 'http://posturl';
    MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
    map.add("id","1");
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
    return restTemplate.postForEntity(url, request,String.class);
  • 不设置请求头

    1
    2
    3
    4
    String url = 'http://posturl';
    MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
    map.add("id","1");
    return restTemplate.postForEntity(url, map,String.class);

欢迎关注我的其它发布渠道