后台调用接口上传文件

一、通过CloseableHttpClient调用,代码如下:

package com.sneb.xiongxin.alarmlogin.util;

import com.sneb.xiongxin.constant.AlarmLoginConstants;
import com.sneb.xiongxin.dto.PushAlarmDTO;
import com.sneb.xiongxin.mapper.ApiRecordMapper;
import com.sneb.xiongxin.util.JsonUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class HttpUtil {

    public final Map<String, ContentType> suffixMap = new HashMap<String, ContentType>() {{
        put("jpg", ContentType.create("image/jpeg", Consts.UTF_8));
        put("tiff", ContentType.create("image/tiff", Consts.UTF_8));
        put("gif", ContentType.create("image/gif", Consts.UTF_8));
        put("jfif", ContentType.create("image/jpeg", Consts.UTF_8));
        put("png", ContentType.create("image/png", Consts.UTF_8));
        put("tif", ContentType.create("image/tiff", Consts.UTF_8));
        put("ico", ContentType.create("image/x-icon", Consts.UTF_8));
        put("jpeg", ContentType.create("image/jpeg", Consts.UTF_8));
        put("wbmp", ContentType.create("image/vnd.wap.wbmp", Consts.UTF_8));
        put("fax", ContentType.create("image/fax", Consts.UTF_8));
        put("net", ContentType.create("image/pnetvue", Consts.UTF_8));
        put("jpe", ContentType.create("image/jpeg", Consts.UTF_8));
        put("rp", ContentType.create("image/vnd.rn-realpix", Consts.UTF_8));
    }};

    @Resource
    private ApiRecordMapper apiRecordMapper;

    @Resource
    private ThreadPoolTaskExecutor simpleExecutor;

    private RestTemplate restTemplate = new RestTemplateBuilder(new org.springframework.boot.web.client.RestTemplateCustomizer[0]).build();

    public String postByForm(String url, MultiValueMap<String, String> map) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity(map, headers);

        String result = String.valueOf(this.restTemplate.postForObject(url, request, String.class, new Object[0]));
        return result;
    }

    public String sendExchangeGet(String url, PushAlarmDTO body, String jwt) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-cache");
        headers.set("Content-Type", "application/json");
        headers.set("Cookie", AlarmLoginConstants.JWT_PRO + jwt);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity(body, headers);
        ResponseEntity<String> response = this.restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class, new Object[0]);
        simpleExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Map<String, Object> insertMap = new HashMap<>();
                    insertMap.put("requestData", JsonUtil.toJson(body, false));
                    insertMap.put("type", "发送");
                    insertMap.put("apiName", url);
                    insertMap.put("responseData", JsonUtil.toJson(response, false));
                    insertMap.put("recordTime", new Date());
                    apiRecordMapper.insert(insertMap);
                } catch (Exception e) {
                    log.warn("新增接口调用记录异常!");
                }
            }
        });
        return response.getBody();
    }

    @SneakyThrows
    public String uploadFile(String fileUrl, String netUrl, String jwt, String warningId, String randomcode, String sectionId) {
        String[] fileUrlSplit = fileUrl.split("/");
        String fileName = fileUrlSplit[fileUrlSplit.length - 1];
        HttpURLConnection httpUrl = (HttpURLConnection) new URL(fileUrl).openConnection();
        try (InputStream inputStream = httpUrl.getInputStream();) {
            httpUrl.connect();
            Map<String, InputStream> inputStreamMap = new HashMap<>();
            inputStreamMap.put(fileName, inputStream);
            Map<String, String> paramMap = new HashMap();
            paramMap.put("warningId", warningId);
            paramMap.put("randomcode", randomcode);
            paramMap.put("sectionId", sectionId);
            paramMap.put("relType", "2");
            paramMap.put("fileType", StringUtils.endsWithAny(fileUrl.toLowerCase(), AlarmLoginConstants.IMAGE_SUFFIX) ? "1" : "2");
            Map<String, String> headlerMap = new HashMap();
            headlerMap.put("Cache-Control", "no-cache");
            headlerMap.put("Cookie", AlarmLoginConstants.JWT_PRO + jwt);
            return doPostInputStream(netUrl, inputStreamMap, paramMap, headlerMap);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            if (httpUrl != null) {
                httpUrl.disconnect();
            }
        }
    }

    /**
     * @param host           请求地址
     * @param inputStreamMap 上传文件
     * @param paramMap       参数
     * @param headlerMap     请求头
     * @return
     * @throws IOException
     */
    public String doPostInputStream(String host, Map<String, InputStream> inputStreamMap, Map<String, String> paramMap, Map<String, String> headlerMap) {
        //添加请求头
        HttpPost httpPost = new HttpPost(host);
        //设置请求属性
        try (CloseableHttpClient httpClient = addHttpClient();
             CloseableHttpResponse response = handleHttpPost(inputStreamMap, paramMap, headlerMap, httpPost, httpClient);) {
            org.apache.http.HttpEntity resEntity = response.getEntity();
            String result = EntityUtils.toString(resEntity, Consts.UTF_8);
            //销毁
            EntityUtils.consume(resEntity);
            return result;
        } catch (Exception e) {
            //返回异常
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
        }
    }

    private CloseableHttpResponse handleHttpPost(Map<String, InputStream> inputStreamMap, Map<String, String> paramMap, Map<String, String> headlerMap, HttpPost httpPost, CloseableHttpClient httpClient) throws IOException {
        for (Map.Entry<String, String> entry : headlerMap.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setCharset(Consts.UTF_8);
        for (Map.Entry<String, InputStream> entry : inputStreamMap.entrySet()) {
            String[] split = entry.getKey().split("\\.");
            ContentType contentType = suffixMap.getOrDefault(split[split.length - 1].toLowerCase(), ContentType.DEFAULT_BINARY);
            multipartEntityBuilder.addBinaryBody("file", entry.getValue(), contentType, entry.getKey());//想要在前端能预览 ContentType 需要修改
        }
        paramMap.forEach((key, value) -> {
            StringBody paramJson = new StringBody(value, ContentType.create("text/plain", Consts.UTF_8));
            multipartEntityBuilder.addPart(key, paramJson);
        });
        org.apache.http.HttpEntity reqEntity = multipartEntityBuilder.build();
        httpPost.setEntity(reqEntity);
        //发送请求
        return httpClient.execute(httpPost);
    }

    /**
     * @return
     */
    public CloseableHttpClient addHttpClient() {
        RequestConfig.Builder builder = RequestConfig.custom();
        //连接超时时间
        builder.setConnectTimeout(AlarmLoginConstants.DEFAULT_CONNECT_TIMEOUT);
        //socket超时时间
        builder.setSocketTimeout(AlarmLoginConstants.DEFAULT_SOCKET_TIMEOUT);
        RequestConfig config = builder.build();
        return HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }

}



二、通过RestTemplate调用,来源于

RestTemplate发送form-data请求上传rul资源文件及对象参数

(https://blog.csdn.net/weixin_44684303/article/details/122963749?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522170666685216800213081786%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=170666685216800213081786&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allfirst_rank_ecpm_v1~rank_v31_ecpm-1-122963749-null-null.142%5Ev99%5Epc_search_result_base4&utm_term=%E7%94%A8restemplate%E5%8F%91%E9%80%81form-data&spm=1018.2226.3001.4187)

package com.sneb.xiongxin.alarmlogin.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sneb.xiongxin.constant.AlarmLoginConstants;
import com.sneb.xiongxin.dto.PushAlarmDTO;
import com.sneb.xiongxin.mapper.ApiRecordMapper;
import com.sneb.xiongxin.util.JsonUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.tomcat.jni.FileInfo;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

@Slf4j
@Component
public class HttpUtil {

    public final Map<String, ContentType> suffixMap = new HashMap<String, ContentType>() {{
        put("jpg", ContentType.create("image/jpeg", Consts.UTF_8));
        put("tiff", ContentType.create("image/tiff", Consts.UTF_8));
        put("gif", ContentType.create("image/gif", Consts.UTF_8));
        put("jfif", ContentType.create("image/jpeg", Consts.UTF_8));
        put("png", ContentType.create("image/png", Consts.UTF_8));
        put("tif", ContentType.create("image/tiff", Consts.UTF_8));
        put("ico", ContentType.create("image/x-icon", Consts.UTF_8));
        put("jpeg", ContentType.create("image/jpeg", Consts.UTF_8));
        put("wbmp", ContentType.create("image/vnd.wap.wbmp", Consts.UTF_8));
        put("fax", ContentType.create("image/fax", Consts.UTF_8));
        put("net", ContentType.create("image/pnetvue", Consts.UTF_8));
        put("jpe", ContentType.create("image/jpeg", Consts.UTF_8));
        put("rp", ContentType.create("image/vnd.rn-realpix", Consts.UTF_8));
    }};

    @Resource
    private ApiRecordMapper apiRecordMapper;

    @Resource
    private ThreadPoolTaskExecutor simpleExecutor;

    private RestTemplate restTemplate = new RestTemplateBuilder(new org.springframework.boot.web.client.RestTemplateCustomizer[0]).build();

    public String postByForm(String url, MultiValueMap<String, String> map) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity(map, headers);

        String result = String.valueOf(this.restTemplate.postForObject(url, request, String.class, new Object[0]));
        return result;
    }

    public String sendExchangeGet(String url, PushAlarmDTO body, String jwt) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-cache");
        headers.set("Content-Type", "application/json");
        headers.set("Cookie", AlarmLoginConstants.JWT_PRO + jwt);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity(body, headers);
        ResponseEntity<String> response = this.restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class, new Object[0]);
        simpleExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Map<String, Object> insertMap = new HashMap<>();
                    insertMap.put("requestData", JsonUtil.toJson(body, false));
                    insertMap.put("type", "发送");
                    insertMap.put("apiName", url);
                    insertMap.put("responseData", JsonUtil.toJson(response, false));
                    insertMap.put("recordTime", new Date());
                    apiRecordMapper.insert(insertMap);
                } catch (Exception e) {
                    log.warn("新增接口调用记录异常!");
                }
            }
        });
        return response.getBody();
    }

    @SneakyThrows
    public String uploadFile(String fileUrl, String netUrl, String jwt, String warningId, String randomcode, String sectionId) {
        String[] fileUrlSplit = fileUrl.split("/");
        String fileName = fileUrlSplit[fileUrlSplit.length - 1];
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache");
        headers.add("Cookie", AlarmLoginConstants.JWT_PRO + jwt);
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
        paramMap.add("warningId", warningId);
        paramMap.add("randomcode", randomcode);
        paramMap.add("sectionId", sectionId);
        paramMap.add("relType", "2");
        paramMap.add("fileType", StringUtils.endsWithAny(fileUrl.toLowerCase(), AlarmLoginConstants.IMAGE_SUFFIX) ? "1" : "2");
        HttpURLConnection httpUrl = (HttpURLConnection) new URL(fileUrl).openConnection();
        try (InputStream inputStream = httpUrl.getInputStream();) {
            paramMap.add("file", new ByteArrayResource(readBytes(inputStream)) {
                @Override
                public String getFilename() {
                    // 指定文件名称
                    return fileName;
                }
            });
            return postFormData(paramMap, netUrl,headers);
        }catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * form-data的post 请求
     * @param netUrl 模块url
     * @param paramMap 请求参数
     * @return
     */
    public  String postFormData(MultiValueMap<String, Object> paramMap, String netUrl, HttpHeaders headers) {
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(paramMap, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(netUrl, httpEntity, String.class);
        return responseEntity.getBody();
    }

    /**
     * 读取输入流到字节数组
     * @param in
     * @return
     * @throws IOException
     */
    public  byte[] readBytes(InputStream in) throws IOException {
        //读取字节的缓冲
        byte[] buffer = new byte[1024];
        //最终的数据
        byte[] result = new byte[0];
        int size = 0;
        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;
    }

}



三、这两种方式主要需要注意各种参数的变化

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值