dromara/hutool

HttpRequest 设置body的时候能否修改isMultiPart的值。

Closed this issue · 4 comments

版本情况

JDK版本: openjdk_8_201
hutool版本: 5.8.27(请确保最新尝试是否还有问题)

问题描述(包括截图)

对接一个阿里云OSS文件上传的需求,需要上传二进制流,且请求的 Content-Type 必须为空(这个上传链接是第三方生成的,我这边改不了),使用 httpRequest.body(inputStreamResource) 上传一直报签名错误,debug看了下,必须带 multipart/form-data 头或 isMultiParttrue 才会走 sendMultipart() 逻辑,能否在设置 body的时候将 isMultiPart 设置为 true 呢? 或者手动设置。 我现在使用反射赋值解决的 😂

  1. 复现代码
public static void buildUploadFile(HttpRequest httpRequest, UploadFile uploadFile) {
            File file = uploadFile.getFile();
            FileChunk chunk = uploadFile.getChunk();
            if (chunk == null) {
                chunk = new FileChunk(0, file.length(), 0);
            }
            try {
                ZopyCopyInputStream byteArrayInputStream = FileUtils.getZopyCopyInputStream(file, chunk.getStart(), chunk.getLength());
                InputStreamResource inputStreamResource = new InputStreamResource(byteArrayInputStream, file.getName());

                if (uploadFile.getUploadType() == UploadType.FORM) {
                    httpRequest.form("file", inputStreamResource);
                } else if (uploadFile.getUploadType() == UploadType.BYTE) {
                    httpRequest.body(inputStreamResource);
                    // 不加这个会签名错误
                    ReflectUtil.setFieldValue(httpRequest, "isMultiPart", true);
                }
            } catch (Exception e) {
                log.error("文件分片设置失败:{}", ExceptionUtil.getMessage(e));
                throw new HttpException("文件分片设置失败", e);
            }
        }

另外能否支持通过 FileChannel 来实现零拷贝上传, 像 asynchttpclient 那样

looly commented

可以借助MultipartBody完成发送:

final MultipartBody body= MultipartBody.create(this.form, this.charset);
body.writeClose(this.getConnection().getOutputStream());

MultipartBody 会带 boundary 值吧。

这个请求还有其他请求头的,这样写我是不是得把 doExecute 给重新实现一遍 😮😮😮。

looly commented

@xweiba 是滴,你也可以自己构建body内容,然后调用body方法,不传Content-Type。