RestTemplate远程调用之传输文件

22 篇文章 0 订阅
5 篇文章 0 订阅

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 groupDescription
getForObjectRetrieves a representation via GET.
getForEntityRetrieves a (that is, status, headers, and body) by using GET.ResponseEntity
headForHeadersRetrieves all headers for a resource by using HEAD.
postForLocationCreates a new resource by using POST and returns the header from the response.Location
postForObjectCreates a new resource by using POST and returns the representation from the response.
postForEntityCreates a new resource by using POST and returns the representation from the response.
putCreates or updates a resource by using PUT.
patchForObjectUpdates 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
deleteDeletes the resources at the specified URI by using DELETE.
optionsForAllowRetrieves allowed HTTP methods for a resource by using ALLOW.
exchangeMore 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``ResponseEntityThese methods allow the use of instead of to specify a response type with generics.ParameterizedTypeReference``Class
executeThe 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配置方式

  1. applicationContext-mvc.xml中配置beanRestTemplate ;

  2. 然后通过 @Autowired或@Resource注解注入RestTemplate对象进行远程调用

applicationContext-mvc.xml配置如下

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>
  1. 通过@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.定义远程传输文件的接口(提供者)

  1. 定义一个uploadOne接口,接收文件参数类型为MultipartFile对象
  2. 接收到传递的文件后,直接上传至Minio服务器种
  3. 如果传递多个文件,将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调用远程接口传递文件(调用者)

  1. 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("远程上传成功");
        }
    }
  • 23
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你好!关于使用RestTemplate进行远程调用,我可以给你一些帮助。RestTemplateSpring框架提供的一个用于发送HTTP请求的客户端工具。你可以使用它来调用其他系统的RESTful API。 首先,你需要在你的项目中导入RestTemplate的依赖。如果你使用的是Maven,可以在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 接下来,你可以在你的代码中使用RestTemplate来发送HTTP请求。下面是一个简单的示例: ```java import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; public class RemoteServiceClient { public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); String url = "http://example.com/api/endpoint"; ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, null, String.class); String responseBody = response.getBody(); System.out.println(responseBody); } } ``` 在上面的示例中,我们创建了一个RestTemplate实例,并使用exchange()方法发送了一个GET请求。你可以根据需要选择合适的HTTP方法(如GET、POST、PUT等)和请求体内容。 当然,在实际应用中,你可能还需要处理错误、设置请求头、传递URL参数等。RestTemplate提供了一些其他的方法和功能来满足这些需求。如果你需要更多细节或更复杂的使用场景,可以查阅Spring官方文档或其他相关资源。 希望这些信息对你有所帮助!如果你有任何其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值