java - 如何在 Android 中使用改造在单个 POST 方法中发布文本数据、单个图像和多个图像?
问题描述
我正在使用改造在单个 POST 请求中发布文本数据、单个图像和多个图像。我尝试了一些方法,但它们对我不起作用。我附上了 PostMan 屏幕截图和我在下面完成的以前的代码。
邮递员截图
我试过的示例代码:
api接口类:
public interface PostSurveyFormApiInterface {
@Multipart
@POST("Shared/InsertDirectSurveyAsync")
Call<ResponseBody> postDirectSurveyForm(@Header("Authorization") String auth,
@Header("Content-Type") String contentType,
@Part("CompanyName") RequestBody companyName,
@Part("Address") RequestBody address,
@Part MultipartBody.Part digitalStamp,
@Part MultipartBody.Part digitalSignature,
@Part MultipartBody.Part[] surveyImage);
}
发布数据的方法:
private void postDataToServer(List<Uri> paths){
RequestBody companyName = RequestBody.create(MediaType.parse("text/plain"), edtCompanyName.getText().toString().trim());
RequestBody address = RequestBody.create(MediaType.parse("text/plain"), edtCompanyAddress.getText().toString());
//for single stamp image
File fileStamp = new File(getRealPathFromURI(stampUri));
RequestBody requestBodyStamp = RequestBody.create(MediaType.parse("image/*"),fileStamp);
MultipartBody.Part stampImagePart = MultipartBody.Part.createFormData("DigitalStamp",
fileStamp.getName(),
requestBodyStamp);
//for single signature image
File fileSignature = new File(getRealPathFromURI(signatureUri));
RequestBody requestBodySignature = RequestBody.create(MediaType.parse("image/*"),fileSignature);
MultipartBody.Part signatureImagePart = MultipartBody.Part.createFormData("DigitalSignature",
fileSignature.getName(),
requestBodySignature);
//for multiple survey(files) images
MultipartBody.Part[] surveyImagesParts = new MultipartBody.Part[paths.size()];
for (int index = 0; index < paths.size(); index++) {
Log.v(TAG,"survey image path \n"+getRealPathFromURI(paths.get(index)));
File file = new File(getRealPathFromURI(paths.get(index)));
RequestBody surveyBody = RequestBody.create(MediaType.parse("image/*"), file);
surveyImagesParts[index] = MultipartBody.Part.createFormData("Files", file.getName(), surveyBody);
}
PostSurveyFormApiInterface apiInterface = ApiClient.getApiClient().create(PostSurveyFormApiInterface.class);
apiInterface.postDirectSurveyForm(
getToken(),
"application/json",
companyName,
address,
stampImagePart,
signatureImagePart,
surveyImagesParts
).enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
progressDialog.dismiss();
if (response.isSuccessful()){
Log.v(TAG,"response successful");
}else{
Log.v(TAG,"failed to post data");
Log.v(TAG,"error : "+response.toString());
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
progressDialog.dismiss();
Log.e(TAG,"error : "+t.getMessage());
}
});
}
请帮助我,我从过去 3 天开始尝试此操作,但无法修复。提前致谢。
解决方案
经过长时间的研究,以下代码对我有用......
PostSurveyFormApi接口
public interface PostSurveyFormApiInterface {
@Multipart
@POST("Shared/InsertDirectSurveyMobileAsync")
Call<ResponseBody> postDirectSurveyForm(@Header("Authorization") String auth,
@Part("CompanyName") RequestBody companyName,
@Part("CompanyAddress") RequestBody address,
@Part MultipartBody.Part digitalStamp,
@Part MultipartBody.Part digitalSignature,
@Part List<MultipartBody.Part> files);
}
发布数据的方法
private void postDataToServer(List<Uri> paths) {
// Request body for Text data (CompanyName)
RequestBody companyName = RequestBody.create(MediaType.parse("text/plain"), edtCompanyName.getText().toString().trim());
// Request body for Text data (Company Address)
RequestBody companyAddress = RequestBody.create(MediaType.parse("text/plain"), edtCompanyAddress.getText().toString().trim());
// Multipart request for single image (Digital Stamp)
MultipartBody.Part digitalStampPart = prepareFilePart("DigitalStamp",stampUri);
// Multipart request for single image (Digital Signature)
MultipartBody.Part digitalSignaturePart = prepareFilePart("DigitalSignature",signatureUri);
//Multipart request for multiple files
List<MultipartBody.Part> listOfPartData = new ArrayList<>();
if (paths != null) {
for (int i = 0; i < paths.size(); i++) {
listOfPartData.add(prepareFilePart("Files[]",paths.get(i)));
}
}
PostSurveyFormApiInterface apiInterface = ApiClient.getApiClient().create(PostSurveyFormApiInterface.class);
apiInterface.postDirectSurveyForm(
getToken(),
companyName,
companyAddress,
digitalStampPart,
digitalSignaturePart,
listOfPartData
).enqueue(new Callback<SurveyPostResponse>() {
@Override
public void onResponse(Call<SurveyPostResponse> call, Response<SurveyPostResponse> response) {
if (response.isSuccessful()) {
Log.v(TAG, "response successful");
} else {
Log.v(TAG, "failed to post data");
}
}
@Override
public void onFailure(Call<SurveyPostResponse> call, Throwable t) {
t.printStackTrace();
Log.e(TAG, "error : " + t.getMessage());
}
});
}
PrepareFilePart方法:
@NonNull
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {
// use the FileUtils to get the actual file by uri
//File file = FileUtils.getFile(this, fileUri);
File file = new File(getRealPathFromUri(mContext, fileUri));
// create RequestBody instance from file
RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), file);
// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}
getRealPathFromUri方法:
// Get Original image path
public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null,null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
推荐阅读
- git - 项目中的 Atlassian Bitbucket 访问存储库
- python - 基于组合 Id 和 Date (Pandas) 的多个聚合
- visual-studio - 如何在 Visual Studio 中的 UWP 和 Win32 项目之间共享 C++ 代码?
- php - 成功登录后产品/登台服务器上的 Laravel sanctum 返回 401
- algorithm - 如何改进用于作业调度的 SA 算法?
- python - 如何检索属于字典类型的 BeautifulSoup 标签文本的键的“值”?
- java - javafx 程序无法连接到 MySQL
- python - Python - 解析graphql,添加一些东西,然后返回查询字符串
- oracle - 在 Oracle APEX 中访问报表输出表
- php - 此集合实例上不存在属性 [img_pers]