RestTemplate远程调用之传输文件
文章目录
1. RestTemplate方法组说明
RestTemplate
The provides a higher level API over HTTP client libraries. It makes it easy to invoke REST endpoints in a single line. It exposes the following groups of overloaded methods:
RestTemplate
通过HTTP客户端库提供了更高级别的API。它使在一行中调用REST端点变得容易。它公开了以下重载方法组:
RestTemplate
Method group | Description |
---|---|
getForObject | Retrieves a representation via GET. |
getForEntity | Retrieves a (that is, status, headers, and body) by using GET.ResponseEntity |
headForHeaders | Retrieves all headers for a resource by using HEAD. |
postForLocation | Creates a new resource by using POST and returns the header from the response.Location |
postForObject | Creates a new resource by using POST and returns the representation from the response. |
postForEntity | Creates a new resource by using POST and returns the representation from the response. |
put | Creates or updates a resource by using PUT. |
patchForObject | Updates a resource by using PATCH and returns the representation from the response. Note that the JDK does not support , but Apache HttpComponents and others do.HttpURLConnection``PATCH |
delete | Deletes the resources at the specified URI by using DELETE. |
optionsForAllow | Retrieves allowed HTTP methods for a resource by using ALLOW. |
exchange | More generalized (and less opinionated) version of the preceding methods that provides extra flexibility when needed. It accepts a (including HTTP method, URL, headers, and body as input) and returns a .RequestEntity``ResponseEntity These methods allow the use of instead of to specify a response type with generics.ParameterizedTypeReference``Class |
execute | The most generalized way to perform a request, with full control over request preparation and response extraction through callback interfaces. |
2. Spring整合RestTemplate
适用场景:SpringBoot、单纯的Spring项目环境、或ssm、ssh项目环境
1. applicationContext.xml配置方式
在
applicationContext-mvc.xml
中配置beanRestTemplate
;然后通过
@Autowired或@Resource
注解注入RestTemplate
对象进行远程调用
applicationContext-mvc.xml
配置如下
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>
- 通过@Autowired注入后使用
DemoController.java
如下
//注入
@Autowired
private RestTemplate restTemplate;
@RequestMapping("/restTest")
public ApiResult restTest(){
String url = "http://localhost:8080";
ResponseEntity<String> forEntity = restTemplate.getForEntity(url+"/app/hello", String.class);
String body = forEntity.getBody();
return ApiResult.success().setMsg(body);
}
2. new RestTemplate对象
在applicationContext-mvc.xml中未配置
RestTemplate
bean ,则通过new 对象的方式调用
Demo1Controller.java
如下
@RequestMapping("/restTest")
public ApiResult restTest(){
//new对象
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080";
ResponseEntity<String> forEntity = restTemplate.getForEntity(url+"/app/hello", String.class);
String body = forEntity.getBody();
return ApiResult.success().setMsg(body);
}
3. SpringBoot环境
SpringBoot环境下直接注入
RestTemplate
对象即可
3. RestTemplate接口调用之单文件传输
使用RestTemplate传送文件,并且有其他字段信息,还有
文件数组
。官网文档:https://docs.spring.io/spring-framework/docs/5.3.25/reference/html/integration.html#rest-client-access
1.定义远程传输文件的接口(提供者)
- 定义一个uploadOne接口,接收文件参数类型为
MultipartFile
对象- 接收到传递的文件后,直接上传至
Minio
服务器种- 如果传递多个文件,将
MultipartFile
对象 改为MultipartFile[]
数组即可
UploadController.java
如下
@PostMapping("/uploadOne")
public ApiResult uploadOne(MultipartFile file, @RequestParam(name = "bucketName", required = false) String bucketName) {
if (file != null) {
if (!StringUtils.hasLength(bucketName)) {
bucketName = defaultBucketName;
}
try {
MinioUtil.uploadObjectByMultipartFile(minioClient, bucketName, MinioUtil.replaceFileName(file.getOriginalFilename()), file);
return ApiResult.success();
} catch (Exception e) {
e.printStackTrace();
return ApiResult.error("上传失败,错误信息:" + e.getMessage());
}
} else {
return ApiResult.error("上传文件不能为空");
}
}
2. RestTemplate调用远程接口传递文件(调用者)
- RestTemplate调用远程接口,传递单个文件
/**
* 获取所有桶信息
*
* @return
*/
@GetMapping("/remoteUploadOne")
public ApiResult remoteUploadOne() {
try {
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
parts.add("bucketName", "yuantest");
parts.add("file", new FileSystemResource("D:\\aa\\files\\aaatest.pdf"));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
ApiResult apiResult = restTemplate.postForObject("http://localhost:7002/std/upload/uploadOne", parts, ApiResult.class);
System.out.println(apiResult.toString());
return ApiResult.success(apiResult.getResult());
} catch (Exception e) {
e.printStackTrace();
return ApiResult.error("远程上传成功");
}
}