Retrofit2.0 上传文件和下载文件
来源:互联网 发布:网络硬件设备 编辑:程序博客网 时间:2024/06/08 13:44
上传文件
Retrofit2.0 需要OkHttp的 RequestBody 或MultipartBody.Part这两个类来实现服务器上传文件。
下面我们看一个简单的定义好的上传文件的接口:
public interface FileUploadService { @Multipart @POST("upload") Call<ResponseBody> upload(@Part("description") RequestBody description, @Part MultipartBody.Part file);}
解释下上面的代码:
- @Part(“description”) 就是RequestBody实例中包裹的字符串值 ;
- @Part MultipartBody.Part file 我们使用MultipartBody.Part类,使我们能够发送实际文件 file就是你要往服务器上传的文件。
下面的这段显示文件的URI作为uploadFile(Uri fileUri)方法的参数。如果你选择一个文件,你会在Android的生命周期的onActivityResult()方法内返回。在这个方法中,你可以得到该文件的URI,你就可以通过uploadFile()这个方法来上传文件。
private void uploadFile(Uri fileUri) { // create upload service client FileUploadService service = ServiceGenerator.createService(FileUploadService.class); // https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java // use the FileUtils to get the actual file by uri File file = FileUtils.getFile(this, fileUri); // create RequestBody instance from file RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file); // MultipartBody.Part is used to send also the actual file name MultipartBody.Part body = MultipartBody.Part.createFormData("picture", file.getName(), requestFile); // add another part within the multipart request String descriptionString = "hello, this is description speaking"; RequestBody description = RequestBody.create( MediaType.parse("multipart/form-data"), descriptionString); // finally, execute the request Call<ResponseBody> call = service.upload(description, body); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { Log.v("Upload", "success"); } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Log.e("Upload error:", t.getMessage()); } });}
下载文件
定义请求Request
// option 1: a resource relative to your base URL@GET("/resource/example.zip")Call<ResponseBody> downloadFileWithFixedUrl();// option 2: using a dynamic URL@GETCall<ResponseBody> downloadFileWithDynamicUrlSync(@Url String fileUrl);
请求
FileDownloadService downloadService = ServiceGenerator.create(FileDownloadService.class);Call<ResponseBody> call = downloadService.downloadFileWithDynamicUrlSync(fileUrl);call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if (response.isSuccess()) { Log.d(TAG, "server contacted and has file"); boolean writtenToDisk = writeResponseBodyToDisk(response.body()); } else { Log.d(TAG, "server contact failed"); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Log.e(TAG, "error"); }});
保存文件
private boolean writeResponseBodyToDisk(ResponseBody body) { try { // todo change the file location/name according to your needs File futureStudioIconFile = new File(getExternalFilesDir(null) + File.separator + "Future Studio Icon.png"); InputStream inputStream = null; OutputStream outputStream = null; try { byte[] fileReader = new byte[4096]; long fileSize = body.contentLength(); long fileSizeDownloaded = 0; inputStream = body.byteStream(); outputStream = new FileOutputStream(futureStudioIconFile); while (true) { int read = inputStream.read(fileReader); if (read == -1) { break; } outputStream.write(fileReader, 0, read); fileSizeDownloaded += read; Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize); } outputStream.flush(); return true; } catch (IOException e) { return false; } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } catch (IOException e) { return false; }}
如果你下载的文件很大,则使用@Streaming 定义Request
@Streaming@GETCall<ResponseBody> downloadFileWithDynamicUrlAsync(@Url String fileUrl);
使用异步方式:
final FileDownloadService downloadService = ServiceGenerator.create(FileDownloadService.class);new AsyncTask<Void, Long, Void>() { @Override protected Void doInBackground(Void... voids) { Call<ResponseBody> call = downloadService.downloadFileWithDynamicUrlSync(fileUrl); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if (response.isSuccess()) { Log.d(TAG, "server contacted and has file"); boolean writtenToDisk = writeResponseBodyToDisk(response.body()); Log.d(TAG, "file download was a success? " + writtenToDisk); } else { Log.d(TAG, "server contact failed"); } } return null; }}.execute();
转载:http://blog.csdn.net/greathfs/article/details/51892499
1 5
- Retrofit2.0 上传文件和下载文件
- Android Retrofit2.0实现文件上传和下载
- Android Retrofit2和Kotlin结合上传文件
- retrofit2上传文件总结
- Retrofit2 使用,文件上传
- retrofit2 文件上传
- retrofit2.0 使用笔记-文件上传功能
- Retrofit2.0上传图片文件件整理
- Retrofit2 & RxJava2实现单文件和多文件上传
- 文件上传和下载
- 文件上传和下载
- 文件上传和下载
- 文件上传和下载
- 文件上传和下载
- 文件上传和下载
- 文件上传和下载
- 文件上传和下载
- 文件上传和下载
- 关于Python文件操作
- json.dumps loads join
- 查询局域网电脑的IP,端口号,MAC地址(黑客技术入门)
- 风不停息!我的第一个博客
- 游戏编程中的人工智能技术-神经网络入门(二)
- Retrofit2.0 上传文件和下载文件
- C++虚函数声明和定义以及g++编译遇到的一些问题
- POJ 2218 Does This Make Me Look Fat?
- java 操作excel
- 封装、继承和多态的具体实例
- CMUSphinx-在你开始之前
- android Button在点击的监听代码里获取自身对象
- 关于python中pymysql数据编码问题
- ubuntu 14.04 linux下wifi驱动安装使用的一些笔记