JAVA调用POST请求接口传递文件

一、引入pom依赖

<!-- 调第三方接口依赖 -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.3</version>
</dependency>

 

二、代码实现

private Long uploadFile(File file) {
        String authorization = crmTokenUtil.getAuthorization();
        String responseJsonString = "";
        CloseableHttpClient httpClient = null;
        try {
            httpClient = HttpClients.createDefault();
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            fileInputStream.read(buffer);
            fileInputStream.close();
            InputStream inputStream = new ByteArrayInputStream(buffer);
            HttpPost httpPost = new HttpPost(requestUrl);
            httpPost.setHeader("Authorization", authorization);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            // 把文件加到HTTP的post请求中
            builder.addBinaryBody("files", inputStream, ContentType.MULTIPART_FORM_DATA, file.getName());
            HttpEntity multipart = builder.build();
            httpPost.setEntity(multipart);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            responseJsonString = EntityUtils.toString(responseEntity, "UTF-8");
            log.info("调用上传文件接口返回结果===>>" + responseJsonString);
 
        } catch (Exception e) {
            log.error("调用上传文件接口失败===>>" + e.getMessage());
            throw new CostAccountingException("调用上传文件接口失败" +  e.getMessage());
        } finally {
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    log.info("调用上传文件接口失败===>>" + e.getMessage());
                    throw new CostAccountingException("调用上传文件接口失败" +  e.getMessage());
                }
            }
        }

  

posted @   一曲终两人遇  阅读(4962)  评论(0编辑  收藏  举报
编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤
点击右上角即可分享
微信分享提示