首先,你需要在你的Gradle文件中添加Retrofit和OkHttp库的依赖:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
接下来,你需要创建一个Retrofit实例并定义你的API接口:
public interface ApiService {
@Multipart
@POST("upload")
Call<ResponseBody> uploadFile(@Part MultipartBody.Part file);
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://your-api-url.com/")
.addConverterFactory(GsonConverterFactory.create())
.client(new OkHttpClient.Builder().build())
.build();
ApiService apiService = retrofit.create(ApiService.class);
在这个例子中,我们定义了一个名为uploadFile
的API方法,它接受一个MultipartBody.Part
参数,它将包含我们要上传的文件。
接下来,你需要创建一个MultipartBody.Part
对象,它将包含你要上传的文件。你可以使用RequestBody.create()
方法来创建一个请求体,它将从文件中读取数据:
File file = new File("path/to/your/file");
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
在这个例子中,我们使用createFormData()
方法来创建一个MultipartBody.Part
对象,它指定了我们要上传的文件的名称和请求体。
最后,你可以调用你的API方法并将MultipartBody.Part
对象作为参数传递:
Call<ResponseBody> call = apiService.uploadFile(filePart);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
// 上传成功
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
// 上传失败
}
});
在这个例子中,我们使用enqueue()
方法来异步执行API调用,并在回调中处理响应或错误。