阿侃,
2022-05-15 13:23
采纳率: 0%
浏览 53
已结题

okhttp请求netty服务器文件下载,数据流获取不到

问题描述:搭建了Netty服务器,将文件信息转换为数据流发送出去,然后通过okhttp去请求,response中有回复,但数据流却没有过来

Netty服务端代码:

    mServerBootstrap.group(mBossGroup, mWorkerGroup)
            .channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    SSLEngine engine = WebSocketUtils.createSslContext().createSSLEngine();
                    engine.setUseClientMode(false);
                    pipeline.addLast(new SslHandler(engine));
                    pipeline.addLast(new HttpServerCodec(4096, 8192, ArchiveStream.BUFFER_SIZE));
                    pipeline.addLast(new HttpObjectAggregator(65536));
                    pipeline.addLast(new LoggingHandler());

                    pipeline.addLast(new ChunkedWriteHandler());
                    pipeline.addLast(new SimpleChannelInboundHandler<Object>() {
                        @Override                                       /////216
                        protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                            FullHttpRequest fullHttpRequest = (FullHttpRequest) msg;
                            handleDownload(ctx, fullHttpRequest);
                            
                        }
                    });
                }
            });
    void handleDownload(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) {
    final ParcelFileDescriptor[] pipes = ParcelFileDescriptor.createPipe();
    final InputStream pipeIn = new BufferedInputStream(new FileInputStream(pipes[0].getFileDescriptor()));
    final OutputStream pipeOut = new BufferedOutputStream(new FileOutputStream(pipes[1].getFileDescriptor()));
    mExecutor.execute(new Runnable() {
        @Override
        public void run() {
            InputStream is = null;

            String path = Environment.getExternalStorageDirectory().getPath() + File.separator + Environment.DIRECTORY_DOWNLOADS;
            File file = new File(path + File.separator + "a.txt");
            is = new FileInputStream(file);
            byte[] buffer = new byte[ArchiveStream.BUFFER_SIZE];            /////623

            int N;
            while (true) {
                try {
                    N = is.read(buffer);
                    if (N < 0) break;
                    pipeOut.write(buffer, 0, N);
                } catch (Exception e) {
                    Log.d(TAG, "read exception");
                    break;
                }
            }
        }
    });
    DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
    ctx.write(response);
    ctx.writeAndFlush(new HttpChunkedInput(new ChunkedStream(pipeIn)));
}

Okhttp请求代码

Request request = new Request.Builder()
            .url("https://" + "10.20.0.148" + ":" + "50000" +"/download?taskId=" + "15802749896")
            .get().build();
    Log.d(TAG, "download request :" + request);

    mOkHttp.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.e(TAG, "onFailure call= " + call , e);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.d(TAG, "onResponse call=" + call + ", reponse=" + response);
            try {
                final InputStream is = response.body().byteStream();

                if (is == null) {
                    System.out.println("is null");
                    return;
                }
                String path = Environment.getExternalStorageDirectory().getPath() +  File.separator + Environment.DIRECTORY_DOWNLOADS;
                File file = new File(path + File.separator + "a.txt");

                byte[] buffer = new byte[ArchiveStream.BUFFER_SIZE];
                try (OutputStream os = new FileOutputStream(file)){
                    while (true) {
                        int N = -1;
                        N = is.read(buffer);
                        System.out.println("read N=" + N);
                        if ( N < 0) break;
                        os.write(buffer, 0, N);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        is.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } finally {
                response.close();
            }
        }
    });

最后出现的问题是,okhttp中response中有回复,但获取到的数据流为空,log信息为:

onResponse call=okhttp3.RealCall@86ad38b, response=Response{protocol=http/1.1, code=200, message=OK, url=https://10.20.0.148:50000/download?taskId=15802749896}
read N=-1

这一端代码也是借鉴的已经可以正常获取数据的代码,但我这里一直无法获取到数据流。
是否有朋友知道问题出在哪里,请求告知,感激不尽

3条回答 默认 最新

相关推荐 更多相似问题