springboot采用HttpClient调用第三方接口,推送zip文件

maven,引入jar包

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>

1,处理多个文件并压缩成zip文件

public void pushzipFile(){

//把所有需要压缩的文件,路径写入实体类
List<DaaffixEntity> selectfj =new ArrayList<DaaffixEntity>();
DaaffixEntity da=new DaaffixEntity();
da.setPath("d:\tp\11.png");
da.setPath("d:\tp\22.pdf");
selectfj.add(da);
//获取文件个数
InputStream[] inputStreamlist = new InputStream[selectfj.size()];
String[] filenames= new String[selectfj.size()];
for (int i = 0; i < selectfj.size(); i++) {
   //获取每一个文件流
    InputStream download = affOperater.download(selectfj.get(i).getPath());
    inputStreamlist[i] = download;
    String filename = selectfj.get(i).getPath().replace("\\", "/");
    filenames[i] = filename.substring(filename.lastIndexOf("/") + 1);
}
File zip = new File("d:\tp\"+ fjdirmap.getAxowner().trim() + ".zip");
log.info("附件zip存放路径:{}",zip.getPath());
//使用ZipUtil.zip工具包进行压缩成zip文件
ZipUtil.zip(zip, filenames, inputStreamlist);
//其他参数
Map<String, String> m = new HashMap<String, String>();
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("OA_ID", fjdirmap.getAxowner().trim());
paramMap.put("FILENAME", fjdirmap.getAxowner().trim() + ".zip");
//调用第三方接口
String loadresponse = HttpClientUtil.doPostUploadFile(oaFileUrl, new HashMap<String, String>(), zip, paramMap);
log.info("附件zip推送响应信息:{}", loadresponse);
JSONObject loadjson = JSONObject.parseObject(loadresponse);

}

2,调用第三方接口,推送zip文件以及其他参数
/**
 * 
 * post请求提交form-data上传文件
 *
 * @param url 第三放接口地址
 * @param headers 请求头
 * @param File zip文件
 * @param paramMap 其他參數
 * @return
 */
public static String doPostUploadFile(String url, Map<String, String> headers, File file, Map<String, String> paramMap) {
    CloseableHttpResponse response = null;
    String respContent = null;
    long startTime = System.currentTimeMillis();
    // 创建Httpclient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(url);
        packageHeader(headers, httpPost);
        String fileName = file.getName();
        // 设置请求头 boundary边界不可重复,重复会导致提交失败
        String boundary = "-------------------------" + UUID.randomUUID().toString();
        httpPost.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
        // 创建MultipartEntityBuilder HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);;
        // 设置字符编码
        builder.setCharset(StandardCharsets.UTF_8);
        // 模拟浏览器
        //builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        // 设置边界
        builder.setBoundary(boundary);
        // application/octet-stream代表不知道是什么格式的文件
        builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, fileName);

        for (Map.Entry<String, String> entry : paramMap.entrySet()) {
            builder.addPart(entry.getKey(), new StringBody(entry.getValue(), ContentType.create("multipart/form-data", Consts.UTF_8)));
        }
        log.info("开始上传");
        HttpEntity entity = builder.build();
        httpPost.setEntity(entity);
        httpPost.setConfig(requestConfig);
        response = httpClient.execute(httpPost);
        if (response != null && response.getStatusLine() != null && response.getStatusLine().getStatusCode() < 400) {
            HttpEntity he = response.getEntity();
            if (he != null) {
                respContent = EntityUtils.toString(he, "UTF-8");
                log.info("上传文件响应信息:{}",respContent);
            }
        } else {
            log.error("对方响应的状态码不在符合的范围内!");
            throw new RuntimeException();
        }
        return respContent;
    } catch (Exception e) {
        log.error("网络访问异常,请求url地址={},响应体={},error={}", url, response, e);
        throw new RuntimeException();
    } finally {
        log.info("统一外网请求参数打印,post请求url地址={},响应={},耗时={}毫秒", url, respContent, (System.currentTimeMillis() - startTime));
        try {
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            log.error("请求链接释放异常", e);
        }
    }
}

3,实体类

@Data
public class DaaffixEntity {
    private String slid;
    private String axowner;
    private String id;
    private String axname;
    private String path;
    private String expd;
    private String axtime;
    private String axorder;
}
  • 9
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值