【下载网页数据流两种写法效果不同】

第一种

public Response downLoadFile(String urlString){
    String[] fileName = urlString.split("/");
    try (InputStream inputStream =new URL(URLDecoder.decode(urlString, "utf-8")).openStream()){
        byte[] b = inputStream.readAllBytes();
        return Response.ok(b)
                .header("Content-Disposition", "attachment;filename=" + fileName[fileName.length-1])
                .header("Content-Length", b.length)
                .build();
    } catch (IOException e) {
        LOG.error("download template failed, exception is:", e);
        throw new ServiceOperationException(ServiceError.DOWNLOAD_FILE_FAILED);
    }
}

第二种 :

public Response downLoadFile(String urlString){
    String[] fileName = urlString.split("/");
    Response.ResponseBuilder response = Response.ok(
            (StreamingOutput) output -> {
                try (InputStream content =new URL(URLDecoder.decode(urlString, "utf-8")).openStream()) {
                    if (content != null) {
                        byte[] b = new byte[2048];
                        int length;
                        while ((length = content.read(b))!= -1) {
                            output.write(b, 0, length);
                        }
                    }
                } catch (IOException e) {
                    LOG.error("download file failed, exception", e);
                    throw new ServiceOperationException(ServiceError.DOWNLOAD_FILE_FAILED);
                }
            });
    response.header("Content-Disposition", "attachment;filename=" + fileName[fileName.length - 1]);
    return response.build();
}

第一种可正常下载文件,第二种汇报序列化错误,具体错误如下:

2022-04-25 14:57:36,121 INFO [res.log] (executor-thread-0) [Response] POST /v1/api/applet/download with result: OK, elapsed: 22.28 ms, req-id: 1234 2022-04-25 14:57:36,122 DEBUG [org.jbo.res.res.i18n] (executor-thread-0) MessageBodyWriter: org.jboss.resteasy.core.providerfactory.SortedKey 2022-04-25 14:57:36,122 DEBUG [org.jbo.res.res.i18n] (executor-thread-0) MessageBodyWriter: io.quarkus.resteasy.common.runtime.jackson.QuarkusJacksonSerializer 2022-04-25 14:57:36,122 DEBUG [org.jbo.res.res.i18n] (executor-thread-0) MessageBodyWriter: io.quarkus.resteasy.common.runtime.jackson.QuarkusJacksonSerializer 2022-04-25 14:57:36,122 DEBUG [org.jbo.res.res.i18n] (executor-thread-0) MessageBodyWriter: org.jboss.resteasy.core.providerfactory.SortedKey 2022-04-25 14:57:36,122 DEBUG [org.jbo.res.res.i18n] (executor-thread-0) Interceptor Context: org.jboss.resteasy.core.interception.jaxrs.ServerWriterInterceptorContext, Method : proceed

先记录下问题,后续解决再更新

第一种:直接把所有字节读入内存

第二种:边读边写

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值