Sending string and images with retrofit multipart/form-data(使用改进的多部分/表单数据发送字符串和图像)
问题描述
我试图发送经过改进的字符串和图像。 虽然我可以使用x-www-form-urlencode&;hashmap获得PASS响应,但我需要将其与图像一起发送。所以我使用表单数据,但是我不能用相同的名称和值得到相同的响应,在Postman上测试它,它和我的x-www-form一样通过。
那么邮递员来了 Postman request that got pass response
未通过的方法 使用表单数据
@Multipart
@POST("report")
fun push(
@HeaderMap headers: Map<String, String>,
@Part("store") string: RequestBody
): Call<ReportingResponse>
RequestBody.create(MediaType.parse("multipart/form-data"), "testing") //#1 fail
RequestBody.create(MediaType.parse("text/plain"), "testing") //#2 fail
我两个都试过了,但没有得到和邮递员一样的回应,看起来就像这样Retrofit request interceptor on Android Studio
使用x-www-form经历的方法
@FormUrlEncoded
@POST("report")
fun push(
@HeaderMap headers: Map<String, String>,
@FieldMap form: MutableMap<String, Any>
): Call<ReportingResponse>
我应该做什么?
推荐答案
第一步:创建调用改版接口的接口方法
@POST(Const.Task_Ans_FILE_NAME)
Call<TaskInfoBean> verifyTaskAns(@Body RequestBody file);
第二步:使用以下代码与正文中的其他字段一起发送分部分图像数据。
RetroFitService retroFitService = RetrofitClient.getAppData();
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
if (answer_type.equals("1")) {
builder.addFormDataPart(Const.ANSWER, answer);
} else {
try {
builder.addFormDataPart(Const.ANSWER, Const.SelectedFileName, RequestBody.create(MultipartBody.FORM, Const.BOS.toByteArray()));
}catch (Exception e){
Log.e(TAG, "doInBackground: "+e.getMessage() );
}
}
builder.addFormDataPart(Const.LOGIN_ID, login_id)
.addFormDataPart(Const.USER_ID, user_id)
.addFormDataPart(Const.PLAY_ID, play_id)
.addFormDataPart(Const.TASK_ID, task_id)
.addFormDataPart(Const.SCENARIO, scenario)
.addFormDataPart(Const.ANSWER_TYPE,answer_type)
.addFormDataPart(Const.SKIP, skip);
final RequestBody requestBody = builder.build();
Call<TaskInfoBean> call = retroFitService.verifyTaskAns(requestBody);
call.enqueue(new Callback<TaskInfoBean>() {
@Override
public void onResponse(Call<TaskInfoBean> call, Response<TaskInfoBean> response) {
if(response.code()==200) {
TaskInfoBean taskInfoBean = response.body();
listener.OnVerifyTaskAns(taskInfoBean);
}else{
Log.e(TAG, "onResponse: "+response.toString() );
}
}
@Override
public void onFailure(Call<TaskInfoBean> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.toString());
}
});
return null;
}
第3步:在您的活动/片段中调用此方法。
这篇关于使用改进的多部分/表单数据发送字符串和图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!