Retrofit2文件上傳下載及其進度顯示


前面一篇文章介紹了Retrofit2的基本使用,這篇文章接着介紹使用Retrofit2實現文件上傳和文件下載,以及上傳下載過程中如何實現進度的顯示。

文件上傳

定義接口
1
2
3
@Multipart
@POST("fileService")
Call<User> uploadFile(@Part MultipartBody.Part file);
構造請求體上傳
1
2
3
4
5
File file = new File(filePath);
RequestBody body = RequestBody.create(MediaType.parse( "application/otcet-stream"), file);
MultipartBody.Part part = MultipartBody.Part.createFormData( "file", file.getName(), body);
Call<User> call = getRetrofitService().uploadOneFile(part);
call.enqueue(callback);

這樣就可以將這個文件上傳到服務器,但就這樣上傳操作不夠友好,最好加上文件上傳進度。而Retrofit本身是不支持文件上傳進度顯示的,所以就需要我們自己擴展OkHttp來實現文件上傳進度。

我的做法是直接擴展一個RequestBody來實現進度顯示,實現完成之后只需要將上面body進行包裝轉換即可

上傳進度顯示
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
RetrofitCallback<User> callback = new RetrofitCallback<User>() {
@Override
public void onSuccess(Call<User> call, Response<User> response) {
runOnUIThread(activity, response.body().toString());
//進度更新結束
}
@Override
public void onFailure(Call<User> call, Throwable t) {
runOnUIThread(activity, t.getMessage());
//進度更新結束
}
@Override
public void onLoading(long total, long progress) {
super.onLoading(total, progress);
//此處進行進度更新
}
};
RequestBody body1 = RequestBody.create(MediaType.parse( "application/otcet-stream"), file);
//通過該行代碼將RequestBody轉換成特定的FileRequestBody
FileRequestBody body = new FileRequestBody(body1, callback);
MultipartBody.Part part = MultipartBody.Part.createFormData( "file", file.getName(), body);
Call<User> call = getRetrofitService().uploadOneFile(part);
call.enqueue(callback);
回調RetrofitCallback
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public abstract class RetrofitCallback<T> implements Callback<T> {
@Override
public void onResponse(Call<T> call, Response<T> response) {
if(response.isSuccessful()) {
onSuccess(call, response);
} else {
onFailure(call, new Throwable(response.message()));
}
}
public abstract void onSuccess(Call<T> call, Response<T> response);
public void onLoading(long total, long progress) {
}
}
FileRequestBody
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* 擴展OkHttp的請求體,實現上傳時的進度提示
*
* @param <T>
*/
public final class FileRequestBody<T> extends RequestBody {
/**
* 實際請求體
*/
private RequestBody requestBody;
/**
* 上傳回調接口
*/
private RetrofitCallback<T> callback;
/**
* 包裝完成的BufferedSink
*/
private BufferedSink bufferedSink;
public FileRequestBody(RequestBody requestBody, RetrofitCallback<T> callback) {
super();
this.requestBody = requestBody;
this.callback = callback;
}
@Override
public long contentLength() throws IOException {
return requestBody.contentLength();
}
@Override
public MediaType contentType() {
return requestBody.contentType();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
if (bufferedSink == null) {
//包裝
bufferedSink = Okio.buffer(sink(sink));
}
//寫入
requestBody.writeTo(bufferedSink);
//必須調用flush,否則最后一部分數據可能不會被寫入
bufferedSink.flush();
}
/**
* 寫入,回調進度接口
* @param sink Sink
* @return Sink
*/
private Sink sink(Sink sink) {
return new ForwardingSink(sink) {
//當前寫入字節數
long bytesWritten = 0L;
//總字節長度,避免多次調用contentLength()方法
long contentLength = 0L;
@Override
public void write(Buffer source, long byteCount) throws IOException {
super.write(source, byteCount);
if (contentLength == 0) {
//獲得contentLength的值,后續不再調用
contentLength = contentLength();
}
//增加當前寫入的字節數
bytesWritten += byteCount;
//回調
callback.onLoading(contentLength, bytesWritten);
}
};
}
}

文件下載

接口定義

文件下載請求與普通的Get和Post請求是一樣的,只是他們的返回值不一樣而已,文件下載請求的返回值一般定義成ResponseBody

1
2
3
4
//這里只舉例POST方式進行文件下載
@FormUrlEncoded
@POST("fileService")
Call<ResponseBody> downloadFile(@Field("param") String param);
發起請求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
RetrofitCallback<ResponseBody> callback = new RetrofitCallback<ResponseBody>() {
@Override
public void onSuccess(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
InputStream is = response.body().byteStream();
String path = Util.getSdCardPath();
File file = new File(path, "download.jpg");
FileOutputStream fos = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.flush();
fos.close();
bis.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
runOnUIThread(activity, t.getMessage());
}
};
 
Call<ResponseBody> call = getRetrofitService(callback).downloadFile(param);
call.enqueue(callback);
下載進度顯示

下載進度顯示有兩種方式實現,一種是通過OkHttp設置攔截器將ResponseBody進行轉換成我們擴展后的ResponseBody(稍后介紹),另外一種則是在上面的回調Callback中將ResponseBody的流寫入到文件時進行進度處理,下面分別進行介紹。

擴展ResponseBody設置OkHttp攔截器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
private <T> RetrofitService getRetrofitService(final RetrofitCallback<T> callback) {
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
clientBuilder.addInterceptor( new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
okhttp3.Response response = chain.proceed(chain.request());
//將ResponseBody轉換成我們需要的FileResponseBody
return response.newBuilder().body(new FileResponseBody<T>(response.body(), callback)).build();
}
});
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(clientBuilder.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitService service = retrofit.create(RetrofitService.class);
return service ;
}
//通過上面的設置后,我們需要在回調RetrofitCallback中實現onLoading方法來進行進度的更新操作,與上傳文件的方法相同
FileResponseBody
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* 擴展OkHttp的請求體,實現上傳時的進度提示
*
* @param <T>
*/
public final class FileResponseBody<T> extends ResponseBody {
/**
* 實際請求體
*/
private ResponseBody mResponseBody;
/**
* 下載回調接口
*/
private RetrofitCallback<T> mCallback;
/**
* BufferedSource
*/
private BufferedSource mBufferedSource;
public FileResponseBody(ResponseBody responseBody, RetrofitCallback<T> callback) {
super();
this.mResponseBody = responseBody;
this.mCallback = callback;
}
@Override
public BufferedSource source() {
if (mBufferedSource == null) {
mBufferedSource = Okio.buffer(source(mResponseBody.source()));
}
return mBufferedSource;
}
@Override
public long contentLength() {
return mResponseBody.contentLength();
}
@Override
public MediaType contentType() {
return mResponseBody.contentType();
}
/**
* 回調進度接口
* @param source
* @return Source
*/
private Source source(Source source) {
return new ForwardingSource(source) {
long totalBytesRead = 0L;
@Override
public long read(Buffer sink, long byteCount) throws IOException {
long bytesRead = super.read(sink, byteCount);
totalBytesRead += bytesRead != - 1 ? bytesRead : 0;
mCallback.onLoading(mResponseBody.contentLength(), totalBytesRead);
return bytesRead;
}
};
}
}
直接在回調中進行進度更新

上面介紹了通過擴展ResponseBody同時設置OkHttp攔截器來實現進度條更新顯示,另外也可以直接在請求回調onSuccess中將流轉換成文件時實現進度更新,下面給出大致實現

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
RetrofitCallback<ResponseBody> callback = new RetrofitCallback<ResponseBody>() {
@Override
public void onSuccess(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
InputStream is = response.body().byteStream();
//獲取文件總長度
long totalLength = is.available();
 
String path = Util.getSdCardPath();
File file = new File(path, "download.jpg");
FileOutputStream fos = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
//此處進行更新操作
//len即可理解為已下載的字節數
//onLoading(len, totalLength);
}
fos.flush();
fos.close();
bis.close();
is.close();
//此處就代表更新結束
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
runOnUIThread(activity, t.getMessage());
}
};

以上就是Retrofit中文件上傳下載及其進度更新顯示的實現


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM