如何在同时向Java / Android中的服务器发送数据的同时在HTTP / 1.1中接收分块响应

问题描述 投票:0回答:1

我们正在构建和应用程序,可以在其上实时记录用户的语音,并通过HTTP请求将记录的数据发送到服务器。当服务器实时处理数据时,它还会分块发送回响应。简而言之,该应用程序正在将数据逐段发送到服务器,同时,它还从服务器接收逐段响应。

[请不要告诉我这是不可能的,因为我在iOS中有一个工作示例,该示例使用URLSessionuploadTask使用流对将数据实时发送到服务器,然后逐块接收响应来自此回调urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)

下面是我在Java中的代码。我已完成发送工作,但仅在完成发送后才收到响应。

RequestBody body = new RequestBody() 
{
    @Override 
    public MediaType contentType() 
    {
        return MediaType.get("application/octet-stream");
    }

    @Override 
    public void writeTo(BufferedSink sink) throws IOException 
    {
        String filename = "/path/spoken.pcm";

        try 
        {
            InputStream inputStream = new DataInputStream(new FileInputStream(new File(filename)));

            byte[] cacheBytes = new byte[320];

            int length;

            while((length = inputStream.read(cacheBytes, 0, cacheBytes.length)) != -1) 
            {
                System.out.println("write thread name: " + Thread.currentThread());

                sink.write(cacheBytes, 0, length);

                Thread.sleep(10);
            }

            inputStream.close();
        } 

        catch(IOException | InterruptedException e) 
        {
            e.printStackTrace();
        }
    }
};

Request request = new Request.Builder()
            .url("www.server.com")
            .post(body)
            .build();

Interceptor interceptor = new Interceptor()
{
    @Override
    public Response intercept(Chain chain) throws IOException 
    {
        System.out.println("intercept!!!");

        CountDownLatch latch = new CountDownLatch(1);

        Response response = chain.proceed(chain.request());
        BufferedSource source = response.body().source();

        System.out.println("got response body !!!!");

        new Thread(new Runnable()
        {
            @Override
            public void run() 
            {
                byte[] cachedBytes = new byte[512];

                try 
                {
                    while(!source.exhausted())
                    {
                        int length = source.read(cachedBytes);
                        byte[] partialBytes = new byte[length];

                        System.arraycopy(cachedBytes, 0, partialBytes, 0, length);

                        System.out.println("partial response received: " + getHexString(partialBytes));
                    }
                } 

                catch (IOException e) 
                {
                    e.printStackTrace();
                }

                latch.countDown();
            }
        }).start();

        try 
        {
            latch.await();
        } 

        catch (InterruptedException e) 
        {
            e.printStackTrace();
        }

        return response;
    }
};

httpClient = new OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .build();

httpClient.newCall(request).enqueue(new Callback() 
{
    @Override
    public void onFailure(Call call, IOException e) 
    {
        e.printStackTrace();
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException 
    {
        try(ResponseBody responseBody = response.body()) 
        {
            if(!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            System.out.println("all responses received!");
        }
    }
});

此日志:System.out.println("got response body !!!!");仅在我将所有数据发送到服务器后才出现。这意味着,当writeTo(BufferedSink sink)返回时,我会在拦截器回调中以块的形式获取响应,然后调用回调onResponse(Call call, Response response)

我需要的是,当我发送数据时,我希望能够同时获得分块的响应。

java okhttp chunked-encoding http-1.1
1个回答
0
投票

对于HTTP / 1.1,在请求主体完成传输之前,OkHttp不会返回响应主体。对于HTTP / 2,您可以覆盖isDuplex()以返回true。

© www.soinside.com 2019 - 2024. All rights reserved.