RestTemplate之Post请求带参数和请求头

1、POST请求带请求头

public Class PostUtils() {

     public static String restTemplatePost(String url, Map<String, String> headerMap,
        MultiValueMap<String, Object> paramMap) {
        try {
            RestTemplate template = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type","application/json");
            headers.add("accept", "text/plain");
            for (String str : headerMap.keySet()) {
                headers.add(str, headerMap.get(str));
            }
            // 不好使的话就把paramMap转为JSONString
            HttpEntity<String> requestParam = new HttpEntity<>(paramMap, headers);
            return template.postForObject(url, requestParam, String.class);
        } catch (Exception e) {
            return e.getMessage();
        }
    }
}

调用

public void useRestTemplatePost() {
    
    Map<String, String> headerMap = new HashMap<>(16);
    headerMap.put("key", "123456");
    MultiValueMap<String, Object> bodyMap = new LinkedMultiValueMap<>();
    bodyMap.put("id", 1);
    String postResult = PostUtils.restTemplatePost("http://xxxxxx", headerMap, bodyMap);
}

2、POST请求不带请求头

/**
 *
 * @param url 请求地址
 * @param paramMap 封装参数
 * @return
 */
public Class PostUtils() {

    public static String restTemplatePost(String url, MultiValueMap<String, Object> paramMap) {

        RestTemplate template = new RestTemplate();
        // 使用postForObject请求接口
        try {
            return template.postForObject(url, paramMap, String.class);
        } catch (Exception e) {
            return e.getMessage();
        }
    }
}

 


版权声明:本文为weixin_47795601原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。