java RestTemplate 发送post请求

RestTemplate简介

RestTemplate是执行HTTP请求的同步阻塞式的客户端,它在HTTP客户端库(如JDK HttpURLConnection,Apache HttpComponents,okHttp等)基础封装了更加简单易用的模板方法API。即RestTemplate是一个封装,底层的实现还是java应用开发中常用的一些HTTP客户端。相对于直接使用底层的HTTP客户端库,它的操作更加方便、快捷,能很大程度上提升我们的开发效率。

case1: POST, 格式:application/json

/**
 * 采用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);
}

 

case2:POST, 格式:application/x-www-form-urlencoded

/**
 * 采用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);
}

 

问题 No beans of 'RestTemplate' type found

使用RestTemplate, 如果直接使用注解

@Autowired
private RestTemplate restTemplate2;

报错:Could not autowire. No beans of 'RestTemplate' type found. 

原因:SpringBoot在版本≥1.4后不再自动定义RestTemplate,而是需要自己手动定义。

解① 自定义Bean

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

 解② 手工自定义

RestTemplate restTemplate = new RestTemplate();
or
private RestTemplate restTemplate = new RestTemplateBuilder()
.setConnectTimeout(Duration.ofSeconds(2))
.setReadTimeout(Duration.ofSeconds(5))
.build();

参考

https://www.4spaces.org/1069.html

https://blog.csdn.net/qq_27130997/article/details/81625845

posted @ 2023-10-10 21:28  jihite  阅读(542)  评论(0编辑  收藏  举报