RestTemplate的Post请求

Spring中有个RestTemplate类用来发送HTTP POST请求很方便,请往下看。

public class RestTemplateUtil {
    
    /**
     * 采用POST请求,数据格式为 application/json,并且返回结果是JSON string
     *
     * @param url
     * @param
     * @return
     */
    public static String postForJson(String url, JSONObject json) {
        RestTemplate restTemplate = new RestTemplate();
        //设置Http Header
        HttpHeaders headers = new HttpHeaders();
        //设置请求媒体数据类型
        headers.setContentType(MediaType.APPLICATION_JSON);
        //设置返回媒体数据类型
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
        return restTemplate.postForObject(url, formEntity, String.class);
    }

    /**
     * 采用POST请求,数据格式为 application/x-www-form-urlencoded,并且返回结果是JSON string
     *
     * @param url 请求地址
     * @param
     * @return
     */
    public static String postInvocation(String url, MultiValueMap<String, Object> param) {
        RestTemplate restTemplate = new RestTemplate();
        //设置Http Header
        HttpHeaders headers = new HttpHeaders();
        //设置请求媒体数据类型
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //设置返回媒体数据类型
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers);
        return restTemplate.postForObject(url, httpEntity, String.class);
    }
}

你可能感兴趣的:(Spring框架解析,spring,spring,boot)