笔记 TestRestTemplate postForObject传递json格式参数

用RestTemplate的postForObject请求其他系统的接口,发现该接口是接收json格式参数,本文只是记录如何用postForObject传递json参数。刚开始用MultiValueMap存放键值对,但是后台json解释出错,后面直接换成HashMap就可以了,注意先把用HttpHeaders把ContentType设置成json格式的

直接上代码

import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

public class TestRestTemplate {


  public static void main(String[] args) {
    testTemp();
  }

  public static void testTemp(){
    RestTemplate restTemplate = new RestTemplate();

    //headers
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.APPLICATION_JSON);
    //body
    //MultiValueMap requestBody = new LinkedMultiValueMap<>();
    Map requestBody = new HashMap();

    requestBody.put("businessKey", "xxxxx");


    //HttpEntity
    HttpEntity> requestEntity = new HttpEntity<>(requestBody, requestHeaders);
    //HttpEntity requestEntity = new HttpEntity(requestBody, requestHeaders);


    String s = restTemplate.postForObject("url", requestEntity,
        String.class);

    System.out.println(s);

  }
}
 

 

你可能感兴趣的:(RestTemplate)