java发送post请求,将文件上传到接口

 业务场景:对接第三方平台接口,将普通参数和文件参数,使用post方式上传到对应接口中

                   当前的文件参数,需要从线上下载到本地在进行传输

接口传输协议:HTTP

接口请求方式:POST

数据编码格式:UTF-8

数据传输格式:multipart/form-data

 具体实现:

 public void organizationReapply() throws Exception {
        String url=ORGANIZATION_REAPPLY;
        //获取httpclient
        CloseableHttpClient client=getHttpClient();
        HttpPost httpPost=new HttpPost(url);
        // 请求参数配置
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000)
                .setConnectionRequestTimeout(10000).build();
        httpPost.setConfig(requestConfig);
        // 获得公共参数
        Map<String, Object> params = sendUtils.commonParams();

        String businessImgPath = "http://xxxx/xxx.png";

        // 从URL下载图片并写入临时文件
        URL imageURL = new URL(businessImgPath);
        URLConnection connection = imageURL.openConnection();
        InputStream imageStream = connection.getInputStream();

        // 创建临时文件
        File tempFile = File.createTempFile("temp_image", ".jpg");

        // 将下载的图片数据写入临时文件
        try (FileOutputStream fos = new FileOutputStream(tempFile)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = imageStream.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
        }

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        //表单中普通参数
        builder.addPart("legalName ",new StringBody("张三", ContentType.create("text/plain", Consts.UTF_8)));
        String contentType = getContentType2(tempFile);

        //表单中文件参数
        builder.addBinaryBody("organizationRegImg", tempFile, ContentType.create(contentType),tempFile.getName());

        HttpEntity entity = builder.build();
        httpPost.setEntity(entity);
        HttpResponse response = client.execute(httpPost);// 执行提交

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String res = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);

            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(res);
            boolean success = jsonNode.get("success").asBoolean();
            //成功,返回邮箱地址
            if (success) {
                JsonNode email = jsonNode.get("data");
                System.out.println("请求发送成功,邮箱地址为:"+email);
            }else{
                String errorMsg = jsonNode.get("msg").asText();
                System.out.println("请求发送失败,失败原因:"+errorMsg);
            }

        } else {
            System.out.println("响应失败:" + response.getStatusLine().getReasonPhrase());
        }
        // 清理临时文件
        tempFile.delete();
        // 关闭HttpClient
        client.close();
    }

获取文件内容类型的代码:

    private String getContentType(File file) {
        // 根据文件后缀名判断内容类型,这里简化处理
        String fileName = file.getName();
        if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
            return "image/jpeg";
        } else if (fileName.endsWith(".png")) {
            return "image/png";
        } else if (fileName.endsWith(".gif")) {
            return "image/gif";
        }
        // 默认返回二进制流类型
        return ContentType.APPLICATION_OCTET_STREAM.getMimeType();
    }

流程:

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值