為了上傳文件到阿里云,使用了阿里云的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的勾選就好了。