【发布时间】:2021-11-29 07:51:33
【问题描述】:
我是新的 Android 开发人员,我正在开发一个应用程序,我的活动是用户可以将他们的项目上传到服务器(文本和图像),但问题是上传文本很容易,我使用 Volley将文本上传到服务器,但我很长时间无法将多个图像上传到服务器。我看到 Retrofit 2 非常适合多文件上传,但我有很多问题。 我尝试了很多但无济于事,我尝试与您分享其中一个代码,以便您帮助我。
我也使用不记名令牌,但我不知道它是否正确。
File file1 = new File(patch_img1);
File file2 = new File(patch_img2);
File file3 = new File(patch_img3);
RequestBody image1 = RequestBody.create(MediaType.parse("image/*"),
file1);
RequestBody image2 = RequestBody.create(MediaType.parse("image/*"),
file2);
RequestBody image3 = RequestBody.create(MediaType.parse("image/*"),
file3);
RequestBody invoice = RequestBody.create(MediaType.parse("text/plain"), invoices);
UserSharedPref sharedPref = new UserSharedPref(CompletedServiceActivity.this);
WebServicesAPI request = APIClient.getApiClient("https://text.com/api/").create(WebServicesAPI.class);
Call<ResponseBody> call = request.upload(sharedPref.getUserToken(),image1,image2,image3,invoice);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
我的界面类
@POST("invoices")
Call<ResponseBody> upload(
@Header("Authorization") String authorization,
@Part("image1") RequestBody image1,
@Part("image2") RequestBody image2,
@Part("image3") RequestBody image3,
@Part("invoice") RequestBody invoice
);
APIClient.class
public class APIClient {
public static Retrofit retrofit = null;
public static Retrofit getApiClient(String url) {
if (retrofit == null) {
Gson gson = new GsonBuilder()
.setLenient()
.create();
retrofit = new Retrofit.Builder().baseUrl(url)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
}
【问题讨论】:
标签: java android retrofit2 bearer-token