这是一种使用改造的方法:
public interface DownloadApi {
@Streaming
@GET("/download")
Call<ResponseBody> download();
}
private Retrofit getRetrofitClient() {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
return builder
.client(httpClient.build())
.build();
}
public void download() {
DownloadApi api = getRetrofitClient().create(DownloadApi.class);
Call<ResponseBody> call = api.download();
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
unzipAndWriteResponseBodyToDisk(response.body());
} else {
//TODO
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
//TODO
}
});
}
private boolean unzipAndWriteResponseBodyToDisk(ResponseBody responseBody) {
try {
InputStream compressedInputStream = new GZIPInputStream(responseBody.byteStream());
InputSource inputSource = new InputSource(compressedInputStream);
InputStream inputStream = new BufferedInputStream(inputSource.getByteStream());
File outputFile = new File("path to your file")
outputFile.getParentFile().mkdirs();
OutputStream outputStream = new FileOutputStream(outputFile.getAbsoluteFile());
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}