RestTemplate发送MultipartFile为参数的请求

package com.rh.user.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.rh.user.untils.JsonFileUtils;
import com.rh.user.untils.RestTemplateUtils;
import com.rh.user.untils.ServiceNode;
import feign.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
public class ControllerUtils {
    @Autowired
    @Qualifier("restTemplate")
    private RestTemplate restTemplate;

    @Autowired
    @Qualifier("loadBalanced")
    private RestTemplate loadBalanced;

    private static Map<String, ServiceNode> serviceMap;
    private static JSONArray array;

    static {
        Resource resource = new ClassPathResource("init.json");
        InputStream inputStream = null;
        //String path = ControllerUtils.class.getClassLoader().getResource("init.json").getPath();

        try {
            inputStream = resource.getInputStream();
            array = JsonFileUtils.getJsonArray(inputStream);
            serviceMap = new HashMap<>();
            System.out.println(array.toJSONString());
            for (int i = 0; i < array.size(); i++) {
                ServiceNode serviceNode = JSON.toJavaObject((JSON) array.get(i), ServiceNode.class);
                serviceMap.put(serviceNode.getService(), serviceNode);
            }
        } catch (IOException e) {
            e.printStackTrace();
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }


    }

@RequestMapping(value = "/transform2/{path}", method = RequestMethod.POST)
    public Object transfrom2(@PathVariable("path") String path, @RequestParam("multipartFile") MultipartFile multipartFile) throws IOException {
        ServiceNode serviceNode = serviceMap.get(path);
        ByteArrayResource fileAsResource = new ByteArrayResource(multipartFile.getBytes()) {
            @Override
            public String getFilename() {
                return multipartFile.getOriginalFilename();
            }

            @Override
            public long contentLength() {
                return multipartFile.getSize();
            }
        };
        MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
        multipartRequest.add("multipartFile", fileAsResource);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity(multipartRequest, headers);
        //发起调用
        return loadBalanced.postForObject(serviceNode.getUrl(), requestEntity, Object.class);
    }

    @RequestMapping("/transform/{path}")
    public Object transfrom(@PathVariable("path") String path, @RequestBody String parms) {
        ServiceNode serviceNode = serviceMap.get(path);
        HttpEntity<String> httpEntity = RestTemplateUtils.createHttpEntity(parms);

        if (serviceNode.getTemplate().equals("restTemplate")) {
            return restTemplate.postForObject(serviceNode.getUrl(), httpEntity, Object.class);
        } else if (serviceNode.getTemplate().equals("loadBalanced")) {
            return loadBalanced.postForObject(serviceNode.getUrl(), httpEntity, Object.class);
        } else {
            return "不支持的格式";
        }
    }

    @RequestMapping(value = "/transform1/{path}", method = RequestMethod.GET)
    public void transform1(@PathVariable("path") String path, @Param("id") int id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        Map<String, String[]> parameterMap = request.getParameterMap();
        String par = "";
        for (String key : parameterMap.keySet()) {
            par += key + "=" + parameterMap.get(key)[0] + "&";
        }
        if (par.endsWith("&")) {
            par = par.substring(0, par.length() - 1);
        }
        HttpEntity<Resource> httpEntity = new HttpEntity<Resource>(headers);

        ServiceNode serviceNode = serviceMap.get(path);
        String url = serviceNode.getUrl();
        if (par.length() != 0) {
            url += "?" + par;
        }
        ResponseEntity<byte[]> response1 = loadBalanced.exchange(url,
                HttpMethod.GET,
                httpEntity, byte[].class);
        HttpHeaders headers1 = response1.getHeaders();

        response.setHeader("Content-Disposition", headers1.getContentDisposition().toString());
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(response1.getBody());
        outputStream.flush();
        outputStream.close();
    }


}

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值