要在Android中使用Retrofit 2上传照片和字符串,您可以按照以下步骤进行操作:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.1'
public class UploadData {
@SerializedName("photo")
private String photo;
@SerializedName("text")
private String text;
public UploadData(String photo, String text) {
this.photo = photo;
this.text = text;
}
// Getters and setters
}
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(logging);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://your-api-url.com/") // 替换为您的实际 API URL
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
@Multipart
注解将请求标记为多部分请求,并使用 @Part
注解来指定要上传的文件和文本字段。public interface UploadService {
@Multipart
@POST("upload")
Call uploadPhotoAndText(
@Part("uploadData") UploadData uploadData,
@Part MultipartBody.Part photoFile
);
}
UploadService uploadService = retrofit.create(UploadService.class);
// 创建一个 File 对象来表示照片文件
File photoFile = new File("/path/to/photo.jpg");
// 创建一个 RequestBody 来封装照片文件
RequestBody photoRequestBody = RequestBody.create(MediaType.parse("image/jpeg"), photoFile);
// 创建一个 MultipartBody.Part 对象来封装照片文件
MultipartBody.Part photoPart = MultipartBody.Part.createFormData("photo", photoFile.getName(), photoRequestBody);
// 创建一个 UploadData 对象来封装字符串字段
UploadData uploadData = new UploadData("Your text", "Your photo");
// 执行上传请求
Call call = uploadService.uploadPhotoAndText(uploadData, photoPart);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if (response.isSuccessful()) {
// 上传成功
} else {
// 上传失败
}
}
@Override
public void onFailure(Call call, Throwable t) {
// 请求失败
}
});
以上就是使用 Retrofit 2 在Android中上传照片和字符串的解决方法。您可以根据您的实际需求进行调整和修改。