OKHTTPCLIENT REQUSET下载文件失败,服务器由Netty构建

发布于 2025-01-28 21:56:38 字数 5224 浏览 3 评论 0原文

现在,我构建了NetTyServer并使用OKHTTP请求下载,但是Okhttp响应没有DataioStream,有人可以帮助我解决问题吗?

代码 的服务器

    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)));
}
    

Netty和客户端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();
            }
        }
    });
}

下载的原因是:Clent可以接收器repoonse日志,但读取缓冲区是错误

onResponse call = okhttp3.realcall@86ad38b,响应=响应{protoct = http/1.1,code = 200,messages = ok,url = https://10.20.0.0.148:50000/download?下载? 阅读n = -1

有人可以告诉我如何解决这个问题吗?谢谢

Now,i build nettyServer and use okHttp request download, but okhttp response not has dataiostream, could someone help me solve the problem?

code
Server by 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)));
}
    

and client okhttp request download

    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();
            }
        }
    });
}

The reason is: clent can receiver repoonse log,but read buffer is error

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

Could someone tell me how to solve this?? Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没有心的人 2025-02-04 21:56:38

defaultfullhttpresponse不能与ChunkedWriteHandler一起使用...因此,在这种情况下,我应该使用Defaulthttresponse而不是默认

DefaultFullHttpResponse cannot use with ChunkedWriteHandler...So in this situation, i should use DefaultHttpResponse instead of DefaultFullHttpResponse

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文