android retrofit2 文件上传
1、build.gradle中添加依赖
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
compile 'com.google.code.gson:gson:2.5'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
2、需实现的API接口类
public interface FileUpload {
/**
* 单文件上传
* @param description
* @param file @Part MultipartBody.Part file 使用MultipartBody.Part类发送文件file到服务器
* @return 状态信息String
*/
@Multipart
@POST("UploadServerAddr")
Call
/**
* 多文件上传:通过 List
* @param parts 每一个part代表一个文件
* @return 状态信息String
*/
@Multipart
@POST("UploadServerAddr")
Call
/**
* 通过 MultipartBody和@body作为参数来实现多文件上传
* @param multipartBody MultipartBody包含多个Part
* @return 状态信息String
*/
@POST("UploadServerAddr")
Call
}
3、 创建OkHttpClient、Retrofit对象
public static final String BASE_URL = "http://×××/UploadFileServer/";
//Log应用拦截器
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//创建OkHttpClient对象
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor) //okHttp的Log应用拦截器
.retryOnConnectionFailure(true)
.connectTimeout(15, TimeUnit.SECONDS)
.build();
//创建Retrofit
Retrofit retrofit = new Retrofit.Builder()
.client(client) //设置OKHttpClient
.baseUrl(BASE_URL) //设置baseUrl, baseUrl必须后缀"/"
.addConverterFactory(GsonConverterFactory.create()) //添加Gson转换器
.build();
4、获取、调用FileUpload的API函数实现单个文件或多文件上传
FileUpload fileUpload = retrofit.create(FileUpload.class); //获取FileUpload的API
// 上传单一文件
String des = "a image";
RequestBody description = RequestBody.create( MediaType.parse("multipart/form-data"), des);
RequestBody requestFile = RequestBody.create(MediaType.parse("text/plain"), new File("/sdcard/0/test.jpg"));
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
Call
call.enqueue(new Callback
@Override
public void onResponse(Call
}
@Override
public void onFailure(Call
}
});
// 上传多文件,参数:List
ArrayList
list.add(new File("/sdcard/0/test0.jpg"));
list.add(new File("/sdcard/0/test1.jpg"));
List
for(File file : list) {
RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
MultipartBody.Part part = MultipartBody.Part.createFormData("image", file.getName(), requestBody);
parts.add(part);
}
Call
call.enqueue(new Callback
@Override
public void onResponse(Call
}
@Override
public void onFailure(Call
}
});
// 上传多文件,参数:MultipartBody对象
ArrayList
list.add(new File("/sdcard/0/test0.jpg"));
list.add(new File("/sdcard/0/test1.jpg"));
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
for(File file : list) {
RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
builder.addFormDataPart("image", file.getName(), requestBody);
}
MultipartBody multipartBody = builder.build(); //List
Call
call.enqueue(new Callback
@Override
public void onResponse(Call
}
@Override
public void onFailure(Call
}
});