欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

RestTemplate发送MultipartFile为参数的请求

程序员文章站 2022-03-04 19:04:58
...
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();
    }


}

 

相关标签: java