使用okhttp进行http请求时,如果post body长度未知,需要使用InputStream作为body传输数据。
okhttp没有提供类似RequestBody.create(File strean)此类快捷调用方法,需要调用者手动构造RequestBody。
参照官方样例,进行修改,如下代码:
https://square.github.io/okhttp/recipes/#post-streaming-kt-java
public static RequestBody createInputStreamRequestBody(final InputStream stream) {
    new okhttp3.RequestBody() {
        @Override
        public MediaType contentType() {
            // 设置body mime类型,这里以二进制流为例
            return MediaType.get("application/octet-stream");
        }
        @Override
        public long contentLength() throws IOException {
            // 返回-1表示body长度未知,将开启http chunk支持
            // RequestBody中默认返回也时-1
            return -1;
        }
        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            try (Source source = Okio.source(stream)) {
                sink.writeAll(source);
            }
        }
    };
}