解决阿里云SDK出现的Stream closed

为了上传文件到阿里云,使用了阿里云的SDK,参照 文档 写了代码:


public static void uploadFile(Context context, String tenantCode, String userToken, String objectName, String filePath) {

    File file = new File(filePath);
    if (!file.exists()) {
        Log.w(TAG, "uploadFile: cannot find the file for upload!!!");
        return;
    }

    OSSClient ossClient = AliYunClient.getInstance(context, tenantCode, userToken).getOssClient();
    PutObjectRequest put = new PutObjectRequest(getBucket(context, tenantCode), objectName, filePath);

    try {
        PutObjectResult request = ossClient.putObject(put);
        String result = request.getServerCallbackReturnBody();
    } catch (ClientException e) {
        e.printStackTrace();
    } catch (ServiceException e) {
        e.printStackTrace();
    }
}

(使用的是SDK2.8.3版本)

然后诡异的是一直报ClientException 这个异常,描述就是:“Stream closed”。我是按照官方标准写的代码呀,不能理解为什么出了问题。没办法,bug还是要改的。追进OKHttp看看发生了什么。

真正发起请求的是OSSRequestTask#call():

public T call() throws Exception {
    Request request = null;
    ResponseMessage responseMessage = null;
    Exception exception = null;
    Call call = null;
    try {
         .......
        switch (message.getMethod()) {
            case POST:
            case PUT:
                OSSUtils.assertTrue(contentType != null, "Content type can't be null when upload!");
                InputStream inputStream = null;
                String stringBody = null;
                long length = 0;
                if (message.getUploadData() != null) {
                    inputStream = new ByteArrayInputStream(message.getUploadData());
                    length = message.getUploadData().length;
                } else if (message.getUploadFilePath() != null) {
                    File file = new File(message.getUploadFilePath());
                    inputStream = new FileInputStream(file);
                    length = file.length();
                } else if (message.getContent() != null) {
                    inputStream = message.getContent();
                    length = message.getContentLength();
                } else {
                    stringBody = message.getStringBody();
                }
                if (inputStream != null) {
                    message.setContent(inputStream);
                    message.setContentLength(length);

                    // 代码走的是这里,构造了一个Request 
                    // 另外NetworkProgressHelper.addProgressRequestBody这里添加了自定义的一个RequestBody
                    requestBuilder = requestBuilder.method(message.getMethod().toString(),
                            NetworkProgressHelper.addProgressRequestBody(inputStream, length, contentType, context));
                } 
            ......

        }
        // 调用OKHttp请求
        call = client.newCall(request);
        ......

重点是这句代码使用了自己的RequestBody,这个RequestBody叫ProgressTouchableRequestBody。

requestBuilder = requestBuilder.method(message.getMethod().toString(),
                            NetworkProgressHelper.addProgressRequestBody(inputStream, length, contentType, context));

ProgressTouchableRequestBody重载了writeTo方法:

public void writeTo(BufferedSink sink) throws IOException { 
  Source source = Okio.source(this.inputStream); 
  long total = 0; 
  long read, toRead, remain; 
  while (total < contentLength) { 
    remain = contentLength - total; 
    toRead = Math.min(remain, SEGMENT_SIZE); 
    read = source.read(sink.buffer(), toRead); 
    if (read == -1) { 
      break; 
    } 
  total += read; 
  sink.flush(); 
  if (callback != null && total != 0) { 
    callback.onProgress(request, total, contentLength); 
    } 
  } 
// 这里close掉了inputStream 
if (source != null) { 
  source.close(); 
  } 
} 

这里Source source = Okio.source(this.inputStream);的source关闭的时候,会将inputstream关闭。

实际调试的时候发现,source.close()总共调用调用了两次。第二次是在发起网络请求时调用的CallServerInterceptor#intercept:

@Override public Response intercept(Chain chain) throws IOException { 
  RealInterceptorChain realChain = (RealInterceptorChain) chain; 
  HttpCodec httpCodec = realChain.httpStream(); 
  StreamAllocation streamAllocation = realChain.streamAllocation(); 
  RealConnection connection = (RealConnection) realChain.connection(); 
  Request request = realChain.request(); 
  long sentRequestMillis = System.currentTimeMillis(); 
  httpCodec.writeRequestHeaders(request); 
  Response.Builder responseBuilder = null; 
  ......
  if (responseBuilder == null) { 
  // Write the request body if the "Expect: 100-continue" expectation was met. 
  Sink requestBodyOut = httpCodec.createRequestBody(request, request.body().contentLength()); 
  BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut); 
 // 这里是第二次调用  
  request.body().writeTo(bufferedRequestBody); 
  bufferedRequestBody.close(); 
   } 
 ......
return response; 
} 

重复执行了ProgressTouchableRequestBody的writeTo方法,第二次执行到read = source.read(sink.buffer(), toRead);时直接崩溃了,因为inputstream已经被close掉了。这就是产生ClientException的原因。

fuck,第一次是谁调用的呢?
幸亏Debug时注意到了OKHttp竟然多出来了一个拦截器:OKHttp3Interceptor,它首先执行了RequestBody的writeTo方法。如下图:

DEBUG

这个拦截器谁加的?找了一下没发现,好气哟。仔细看了一眼包名:com.android.tools.profiler.agent.okhttp。嗯,貌似是Android Profiler相关?因为Android Profiler可以分析Network呀,为了分析OKHttp的网络请求肯定要加拦截器的。因此看了一眼我的Profiling开关果然是开着的:
profiling

去掉这个勾,重试,哇擦,成功了。。。原来问题就出现在这里。

总结

出现Stream closed的原因是打开了Android Profiler,额外添加了一个拦截器,这个拦截器关闭了Inputstream。导致真正执行网络请求时,想要使用这个Inputstream,发现这个Inputstream已经关闭了,抛出了一个异常。很好解决,去掉Android Profiler的勾选就好了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 关于okhttp是一款优秀的网络请求框架,关于它的源码分析文章有很多,这里分享我在学习过程中读到的感觉比较好的文章...
    蕉下孤客阅读 3,616评论 2 38
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,860评论 18 139
  • 参考Android网络请求心路历程Android Http接地气网络请求(HttpURLConnection) 一...
    合肥黑阅读 21,332评论 7 63
  • 参考资源 官网 国内博客 GitHub官网 鉴于一些关于OKHttp3源码的解析文档过于碎片化,本文系统的,由浅入...
    风骨依存阅读 12,555评论 11 82
  • 当青春从象牙塔逃离的那一刻,我们毫不犹豫的告别了寒冷的世界,带着落叶归根的心绪在一片平静的城堡里当起了自己的国王,...
    温失旧岛丶阅读 423评论 1 1