用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);// 获取文件真实的minetypeMap<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 设计指南