Spring - Spring Boot作为接口转发器和文件转发器的实现

Spring Boot作为接口转发器和文件转发器的实现

接口转发

controller

    @ResponseBody
    @PostMapping("/adapter-test")
    public JSONObject adapterTest(@RequestBody Map<String, Object> requestMap) {
        return testService.adapterTest(requestMap);
    }

service

    @Autowired
    private RestTemplate restTemplate;

    public JSONObject adapterTest(Map<String, Object> requestMap) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        // 鉴权用,可选
        headers.add("Authorization", "Bearer xxxxx");

        String remoteUrl = requestMap.get("remoteUrl").toString();

        JSONObject remoteRequestMap = new JSONObject();
        remoteRequestMap.putAll(requestMap);
        HttpEntity<JSONObject> entity = new HttpEntity<>(remoteRequestMap, headers);

        return restTemplate.postForObject(remoteUrl, entity, JSONObject.class);
    }

request demo

{
    ...
    "remoteUrl":"http://..."
}

文件转发

controller

    @ResponseBody
    @PostMapping("/file-adapter-test")
    public JSONObject fileAdapterTest(@RequestParam(value = "remoteUrl") String remoteUrl, MultipartFile file) {
        return testService.fileAdapterTest(remoteUrl, file);
    }

service

    public JSONObject fileAdapterTest(String remoteUrl, MultipartFile file) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType(MediaType.MULTIPART_FORM_DATA_VALUE);
        headers.setContentType(type);
        // 鉴权用,可选
        headers.add("Authorization", "Bearer xxxxx");

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();

        // 转换成File对象
        String fileName = file.getOriginalFilename();
        Assert.notNull(fileName, "获取上传的原始文件名不能为空");
        File localFile = new File(fileName);
        try (OutputStream out = new FileOutputStream(localFile)) {
            // 输入流和输出流之间的拷贝
            FileCopyUtils.copy(file.getInputStream(), out);
            // 文件转换并设置为参数
            params.add("file", new FileSystemResource(localFile));
        } catch (IOException e) {
            throw new ServiceException("上传的文件转换异常");
        }
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(params, headers);
        JSONObject resultJson = restTemplate.postForObject(remoteUrl, entity, JSONObject.class);

        // 删掉缓存的文件
        localFile.delete();

        return resultJson;
    }

request demo

 

posted @ 2022-06-14 10:02  Helios_Fz  阅读(1603)  评论(0编辑  收藏  举报