Springboot使用RestTemplate请求post的MULTIPART_FORM_DATA接口

package com.maxnerva.cloudmes.utils.common;

import cn.hutool.core.util.ObjectUtil;
import com.maxnerva.cloudmes.common.utils.WebContextUtil;
import com.maxnerva.cloudmes.model.mail.MailRequestDTO;
import com.maxnerva.cloudmes.model.mail.MailResponseDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author lrx
 * @description: TODO  HTTP客户端工具类
 * @date 2022/2/17 15:30
 */
@Service
@Slf4j
public class HttpUtil {
    @Value("${platform.gateway}")
    private String paasUrl;
    @Value("${platform.mailUrl}")
    private String mailUrl;

    public MailResponseDTO sendMail(MailRequestDTO mailRequestDTO) throws IOException {

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<String, Object>();
        params.add("mailTo", mailRequestDTO.getMailTo());
        params.add("mailCc", mailRequestDTO.getMailCc());
        params.add("mailTitle", mailRequestDTO.getMailTitle());
        params.add("mailBody", mailRequestDTO.getMailBody());
        //通过url获取文件资源
        ByteArrayResource contentsAsResource = getResourceByUrl("null", "null");
        params.add("file", contentsAsResource);

        MailResponseDTO mailResponseDTO = postFormData(params);
        return mailResponseDTO;
    }

    /**
     * form-data的post 请求
     *
     * @param params 请求参数
     * @return
     */
    public MailResponseDTO postFormData(MultiValueMap<String, Object> params) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("token", WebContextUtil.getContext().getCurrToken());
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(params, headers);
        log.info("++++a" + httpEntity.toString());
        ResponseEntity<MailResponseDTO> responseEntity = restTemplate.postForEntity(paasUrl + mailUrl, httpEntity, MailResponseDTO.class);

        //ResponseEntity<String> responseEntity = restTemplate.exchange(urlHeader+modelUrl, HttpMethod.POST, httpEntity, String.class);
        return responseEntity.getBody();

    }

    /**
     * 通过url获取文件资源
     *
     * @param url
     * @param fileName
     * @return
     * @throws IOException
     */
    private static ByteArrayResource getResourceByUrl(String url, String fileName) throws IOException {
        // 通过url获取输入流
        InputStream inputStream = getFileInputStream(url);
        // 读取输入流到字节数组
        byte[] bytes = readBytes(inputStream);
        // 将自己数组转为文件资源
        return new ByteArrayResource(bytes) {
            @Override
            public String getFilename() {
                // 指定文件名称
                return fileName;
            }
        };
    }

    /*读取网络文件*/
    public static InputStream getFileInputStream(String path) {
        URL url = null;
        try {
            url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(3 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //得到输入流
            return conn.getInputStream();
        } catch (Exception e) {
            log.error("读取网络文件异常:" + path);
        }
        return null;
    }

    /**
     * 读取输入流到字节数组
     *
     * @param in
     * @return
     * @throws IOException
     */
    public static byte[] readBytes(InputStream in) throws IOException {
        //读取字节的缓冲
        byte[] buffer = new byte[1024];
        //最终的数据
        byte[] result = new byte[0];
        int size = 0;
        if (ObjectUtil.isNull(in)) {
            return result;
        }
        while ((size = in.read(buffer)) != -1) {
            int oldLen = result.length;
            byte[] tmp = new byte[oldLen + size];
            if (oldLen > 0) {//copy 旧字节
                System.arraycopy(result, 0, tmp, 0, oldLen);
            }
            //copy 新字节
            System.arraycopy(buffer, 0, tmp, oldLen, size);

            result = tmp;
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/LRXmrlirixing/article/details/129121357