SpringBoot使用RestTemplate
初始化
使用Configuration 加入IOC容器 的配置:
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
@Configuration
public class RestTemplateConfiguration {
@Bean
public RestTemplate restTemplate() {
SimpleClientHttpRequestFactory requestFactory =
new SimpleClientHttpRequestFactory();
// 设置连接超时,单位毫秒
requestFactory.setConnectTimeout(30000);
//设置读取超时
requestFactory.setReadTimeout(30000);
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(requestFactory);
restTemplate.getMessageConverters().add(
new StringHttpMessageConverter(StandardCharsets.UTF_8)
);
restTemplate.getMessageConverters().add(
new FastJsonHttpMessageConverter()
);
return restTemplate;
}
}
如果想不加入IOC容器的话,可以使用如下单例方式。
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
public class RestTemplateProvider {
private static final RestTemplate restTemplate = init();
private RestTemplateProvider() {
}
public static RestTemplate getRestTemplate() {
return restTemplate;
}
private static RestTemplate init() {
SimpleClientHttpRequestFactory requestFactory =
new SimpleClientHttpRequestFactory();
// 设置连接超时,单位毫秒
requestFactory.setConnectTimeout(30000);
//设置读取超时
requestFactory.setReadTimeout(30000);
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(requestFactory);
restTemplate.getMessageConverters().add(
new StringHttpMessageConverter(StandardCharsets.UTF_8)
);
restTemplate.getMessageConverters().add(
new FastJsonHttpMessageConverter()
);
return restTemplate;
}
}
POST请求
(1)发送JSON格式
参数:
@Data
public class TaskDO {
private String id;
}
客户端调用
TaskDO taskDO = new TaskDO();
taskDO.setId("20220113");
String url = "http://localhost:8080/dispatch";
//或者使用Map也可以
//Map<String,Object> params = new HashMap<>();
//params.put("id","20220113");
//String result = restTempalte.postForObject(url , params, String.class);
String result = restTempalte.postForObject(url , taskDO, String.class);
//String.class是返回值,可以输入Object.class、Map.class等任何返回值,需要约定好哦
//Map result = restTempalte.postForObject(url , taskDO, Map.class);
//Object result = restTempalte.postForObject(url , taskDO, Object.class);
//Response result = restTempalte.postForObject(url , taskDO, Response.class);
Controller接收
@PostMapping("/dispatch")
public SingleResponse function(@RequestBody @Valid TaskDO params) {
LOGGER.info("参数是:{}", params);
jobTask.executeTask(params);
return SingleResponse.of("成功");
}
(2)发送普通表单格式
@Data
public class TaskDO {
private String id;
private String taskName;
}
客户端调用
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
String url = "http://localhost:8080/dispatch";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//提交参数设置
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("id", "20220113");
map.add("taskName", "我的任务");
// 组装请求体
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
String result = restTempalte.postForObject(url, request, String.class);
System.out.println(result);
Controller接收
@PostMapping("/dispatch")
public SingleResponse function(TaskDO params) {
LOGGER.info("参数是:{}", params);
return SingleResponse.of("成功");
}
(3)上传文件
private static RestTemplate init() {
SimpleClientHttpRequestFactory requestFactory =
new SimpleClientHttpRequestFactory();
// 设置连接超时,单位毫秒
requestFactory.setConnectTimeout(30000);
//设置读取超时
requestFactory.setReadTimeout(30000);
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(requestFactory);
restTemplate.getMessageConverters().add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());
return restTemplate;
}
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.core.io.FileSystemResource;
MultiValueMap<String,Object> parts = new LinkedMultiValueMap<>();
parts.add("file", new FileSystemResource(new File("C:\\test.txt")));
parts.add("num", 5);
parts.add("flag", true);
String url = "http://localhost:8080/upload";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String,Object>> request = new HttpEntity<>(parts, headers);
ResponseEntity<String> entity =
restTemplate.exchange(url, HttpMethod.POST, request, String.class);
System.out.println(entity.getBody());
@Data
public class UploadCmd implements Serializable {
private Integer num;
private Boolean flag;
private MultipartFile file;
}
@PostMapping(value = "/upload")
public Response upload(UploadCmd upload) throws IOException {
...
}
GET请求
GET请求的参数使用 {} 占位,注意,是{} ,不是 ${}
@Data
public class TaskDO {
private String taskName;
private Integer num;
private Boolean flag;
}
String url = "http://localhost:8080/get?num={id}&taskName={taskName}&flag={f}";
String result = restTemplate.getForObject(url, String.class,5,"我的任务",true);
@GetMapping(value = "/get")
public TaskDO get(TaskDO paramType) {
return paramType;
}