安卓接阿里云OSS出现read failed: EBADF (Bad file descriptor)

亲测有效,解决:com.alibaba.sdk.android.oss.ClientException: read failed: EBADF (Bad file descriptor)

 

解决:

Android Studio中 Run --> EditConfigurations -->Profiling取消勾选即可

 

原因:

为了上传文件到阿里云,使用了阿里云的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方法

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


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

 

总结

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




参考文章:https://www.jianshu.com/p/3608630af86a

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值