hutool HttpRequest.post 请求包含大文件报错Java heap space

hutool版本: hutool-all-5.7.20

hutool官网文档:Http请求-HttpRequest | Hutool

请求代码,file小于700m正常请求,大于700m就报错java.lang.OutOfMemoryError: Java heap space

 HttpResponse response = HttpRequest.post(urlStr)
                  
                    .form("bid_section_no", req.getBid_section_no())
                    .form("type", req.getType())
                    .form("file", file)
                    .execute();

 具体异常如下,可以定位到是execute执行请求时抛出的,有一点需要注意,try catch (Throwable e)才能打印出改异常,用Exception还打印不出来。。

09:42:21.155 ERROR [o5zclD18cbb4d076] ive.service.ElectronicArchiveService 578  - 【档案系统对接】推送附件信息异常:{} java.lang.OutOfMemoryError: Java heap space
	at java.util.Arrays.copyOf(Arrays.java:3236) ~[?:1.8.0_241]
	at java.io.ByteArrayOutputStream.grow(ByteArrayOutputStream.java:118) ~[?:1.8.0_241]
	at java.io.ByteArrayOutputStream.ensureCapacity(ByteArrayOutputStream.java:93) ~[?:1.8.0_241]
	at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:135) ~[?:1.8.0_241]
	at sun.net.www.http.PosterOutputStream.write(PosterOutputStream.java:63) ~[?:1.8.0_241]
	at cn.hutool.http.MultipartOutputStream.write(MultipartOutputStream.java:108) ~[hutool-all-5.7.20.jar:?]
	at java.io.OutputStream.write(OutputStream.java:116) ~[?:1.8.0_241]
	at cn.hutool.core.io.copy.StreamCopier.doCopy(StreamCopier.java:102) ~[hutool-all-5.7.20.jar:?]
	at cn.hutool.core.io.copy.StreamCopier.copy(StreamCopier.java:68) ~[hutool-all-5.7.20.jar:?]
	at cn.hutool.core.io.IoUtil.copy(IoUtil.java:162) ~[hutool-all-5.7.20.jar:?]
	at cn.hutool.core.io.IoUtil.copy(IoUtil.java:146) ~[hutool-all-5.7.20.jar:?]
	at cn.hutool.core.io.IoUtil.copy(IoUtil.java:132) ~[hutool-all-5.7.20.jar:?]
	at cn.hutool.core.io.IoUtil.copy(IoUtil.java:119) ~[hutool-all-5.7.20.jar:?]
	at cn.hutool.core.io.resource.Resource.writeTo(Resource.java:65) ~[hutool-all-5.7.20.jar:?]
	at cn.hutool.http.MultipartOutputStream.appendResource(MultipartOutputStream.java:163) ~[hutool-all-5.7.20.jar:?]
	at cn.hutool.http.MultipartOutputStream.write(MultipartOutputStream.java:96) ~[hutool-all-5.7.20.jar:?]
	at cn.hutool.http.body.MultipartBody$$Lambda$1195/1472378755.accept(Unknown Source) ~[?:?]
	at java.util.LinkedHashMap.forEach(LinkedHashMap.java:684) ~[?:1.8.0_241]
	at cn.hutool.http.body.MultipartBody.write(MultipartBody.java:78) ~[hutool-all-5.7.20.jar:?]
	at cn.hutool.http.body.RequestBody.writeClose(RequestBody.java:27) ~[hutool-all-5.7.20.jar:?]
	at cn.hutool.http.HttpRequest.sendMultipart(HttpRequest.java:1260) ~[hutool-all-5.7.20.jar:?]
	at cn.hutool.http.HttpRequest.send(HttpRequest.java:1214) ~[hutool-all-5.7.20.jar:?]
	at cn.hutool.http.HttpRequest.doExecute(HttpRequest.java:1106) ~[hutool-all-5.7.20.jar:?]
	at cn.hutool.http.HttpRequest.execute(HttpRequest.java:997) ~[hutool-all-5.7.20.jar:?]
	at cn.hutool.http.HttpRequest.execute(HttpRequest.java:973) ~[hutool-all-5.7.20.jar:?]
	at cn.pinming.jsgc.thirds.pusharchive.service.ElectronicArchiveService.pushArchiveFile(ElectronicArchiveService.java:570) ~[classes/:5.0-SNAPSHOT]
	at cn.pinming.jsgc.thirds.pusharchive.service.ElectronicArchiveService$$FastClassBySpringCGLIB$$9ed1858e.invoke(<generated>) ~[classes/:5.0-SNAPSHOT]
	at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749) ~[spring-aop-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.transaction.interceptor.TransactionInterceptor$$Lambda$698/1208319854.proceedWithInvocation(Unknown Source) ~[?:?]
	at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294) ~[spring-tx-5.1.5.RELEASE.jar:5.1.5.RELEASE]

09:42:21.374 ERROR [o5zclD18cbb4d076] ive.service.ElectronicArchiveService 579  - java.lang.OutOfMemoryError: Java heap space

经过一番查找发现可以设置个属性避免内存问题,setChunkedStreamingMode

//这个方法表示不使用PosterOutputStream而使用HttpURLConnection$StreamingOutputStream
//防止OutOfMemory。

setChunkedStreamingMode(0) 就是表示使用PosterOutputStream输出流,会把文件全部缓存到内存后发送,需要设置对应分块大小,例如setChunkedStreamingMode(4096)才会使用StreamingOutputStream输出流

最终改成如下方式成功请求并返回

HttpResponse response = HttpRequest.post(urlStr)
                    .setChunkedStreamingMode(4096)
                    .form("bid_section_no", req.getBid_section_no())
                    .form("type", req.getType())
                    .form("file", file)
                    .execute();

BUD.....

14:18:44.649 DEBUG [U32T1k18ccd4f103] pping.InterfaceLogParamMapper.insert 137  - <==    Updates: 1
cn.hutool.core.io.IORuntimeException: IOException: Error writing request body to server
    at cn.hutool.core.io.copy.StreamCopier.copy(StreamCopier.java:71)
    at cn.hutool.core.io.IoUtil.copy(IoUtil.java:162)
    at cn.hutool.core.io.IoUtil.copy(IoUtil.java:146)
    at cn.hutool.core.io.IoUtil.copy(IoUtil.java:132)
    at cn.hutool.core.io.IoUtil.copy(IoUtil.java:119)
    at cn.hutool.core.io.resource.Resource.writeTo(Resource.java:65)
    at cn.hutool.http.MultipartOutputStream.appendResource(MultipartOutputStream.java:163)
    at cn.hutool.http.MultipartOutputStream.write(MultipartOutputStream.java:96)
    at java.util.LinkedHashMap.forEach(LinkedHashMap.java:684)
    at cn.hutool.http.body.MultipartBody.write(MultipartBody.java:78)
    at cn.hutool.http.body.RequestBody.writeClose(RequestBody.java:27)
    at cn.hutool.http.HttpRequest.sendMultipart(HttpRequest.java:1260)
    at cn.hutool.http.HttpRequest.send(HttpRequest.java:1214)
    at cn.hutool.http.HttpRequest.doExecute(HttpRequest.java:1106)
    at cn.hutool.http.HttpRequest.execute(HttpRequest.java:997)
    at cn.hutool.http.HttpRequest.execute(HttpRequest.java:973)

最后换种方式可以了

         // 创建 HttpClient 实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建 HttpPost 实例,并指定 URL
        HttpPost httpPost = new HttpPost(urlStr);
        try {
            // 创建 MultipartEntityBuilder 实例
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            // 设置编码,解决中文乱码问题
            builder.setCharset(Charset.forName("UTF-8"));
            // 设置浏览器兼容模式
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            // 添加文本字段
            builder.addTextBody("type", req.getType());
            builder.addTextBody("bid_section_no", req.getBid_section_no());
            // 添加文件
            builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, file.getName());
            // 构建 HttpEntity
            HttpEntity multipart = builder.build();
            // 设置请求实体
            httpPost.setEntity(multipart);
            // 执行请求并获得响应
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            String resEntity = EntityUtils.toString(responseEntity, "UTF-8");
            System.out.println("resEntity:" + resEntity);
            // 关闭响应
            response.close();
            result = JSON.parseObject(resEntity, ApiResult.class);
        } catch (Exception ex) {
            System.out.println(MessageFormat.format("LargeFileUpload方法错误信息:{0}", ex.getLocalizedMessage()));
        }catch (Throwable e){
            e.printStackTrace();
            logger.error("【档案系统对接】推送附件信息异常:{}", e);
        } finally {
            try {
                // 关闭 HttpClient 实例
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;

 

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>