retrofit2.0 使用笔记-文件上传功能

用2.0做了个文件上传的功能,期望返回的字符串,在网上各种搜索,也没有找到合适的。基本都是已经解析后的java对象。

定义上传接口

public interface ApiInterface {
    @Multipart
    @POST("http://****")
    Call<ResponseBody> upload(@PartMap Map<String, RequestBody> params);
}
文件上传方法:
private void uploadTest() {
        String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        File file1 = new File(rootPath + "/test.docx");
        File file2 = new File(rootPath + "/test2.rar");
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("***")
//                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ApiInterface apiService = retrofit.create(ApiInterface.class);
        // 获取文件真实的minetype
        Map<String, RequestBody> params = new HashMap<>();
        String mimeType = MimeTypeMap.getSingleton()
                .getMimeTypeFromExtension(
                        MimeTypeMap.getFileExtensionFromUrl(file1.getPath()));
        String mimeType2 = MimeTypeMap.getSingleton()
                .getMimeTypeFromExtension(
                        MimeTypeMap.getFileExtensionFromUrl(file2.getPath()));
        // 网上看了大量的都是传的image/png,或者image/jpg 啥的,这个参数还不是很明白,需要跟下源码在研究下。用这个minetype文件能上传成功。
        RequestBody fileBody = RequestBody.create(MediaType.parse(mimeType), file1);
        RequestBody fileBody2 = RequestBody.create(MediaType.parse(mimeType2), file2);
        params.put("file\"; filename=\"" + file1.getName() + "", fileBody);
        params.put("file\"; filename=\"" + file2.getName() + "", fileBody2);
        Call<ResponseBody> call = apiService.upload(params);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String jsonString = new String(response.body().bytes()); // 这就是返回的json字符串了。
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable throwable) {

            }
        });
    }

网上说这么写能够上传多张文件。但是我测试发现返回的json信息中显示的是只有一个文件成功收到返回信息了。具体原因还不清楚。可能是服务器接收文件处理的问题。还需要调整。


附录:

retrofit 2.0 源码解析:

http://bxbxbai.github.io/2015/12/13/retrofit2/

retrofit官方文档
用 Retrofit 2 简化 HTTP 请求
使用Retrofit请求API数据
Retrofit2 更新指南
RESTful API 设计指南

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值