Android 在@body上改装@multipart有问题 类类型对象中的映像多部分。 案例1。(我已经做到了)
服务参数:Android 在@body上改装@multipart有问题 类类型对象中的映像多部分。 案例1。(我已经做到了),android,annotations,retrofit2,Android,Annotations,Retrofit2,服务参数: {"id":"1","name":"vishal","image/file":""} 当时我的API的改装 @Multipart @POST("webservice") Call<SignUpResp> loadSignupMultipart(@Part("description") RequestBody description, @Part MultipartBody.Part file, @QueryMap HashMap<String, String&g
{"id":"1","name":"vishal","image/file":""}
当时我的API
的改装
@Multipart
@POST("webservice")
Call<SignUpResp> loadSignupMultipart(@Part("description") RequestBody description, @Part MultipartBody.Part file, @QueryMap HashMap<String, String> params);
Java端
我不知道为什么,但它返回的错误如下:
“@正文参数不能与表单或多部分编码一起使用”
任何帮助都将不胜感激。将您的方法更改为
@Multipart
@POST("users/{id}/user_photos")
Call<models.UploadResponse> uploadPhoto(@Path("id") int userId, @PartMap Map<String, RequestBody> params);
@Multipart
@POST(“用户/{id}/user_照片”)
调用uploadPhoto(@Path(“id”)int userId,@PartMap-Map-params);
现在要创建请求参数
//All the String parameters, you have to put like
Map<String, RequestBody> map = new HashMap<>();
map.put("methodName", toRequestBody(methodName));
map.put("userid", toRequestBody(userId));
map.put("relation", toRequestBody(relation));
map.put("icon_type", toRequestBody(iconType));
map.put("icon_id", toRequestBody(iconId));
map.put("name", toRequestBody(name));
map.put("relation_id", toRequestBody(relationId));
//To put your image file you have to do
File file = new File("file_name");
RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"), file);
map.put("relative_image\"; filename=\"some_file_name.png\"", fileBody);
// This method converts String to RequestBody
public static RequestBody toRequestBody (String value) {
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), value);
return body ;
}
//To send your request
call = service.loadLevel1halfIconswithImage(description, params);
//所有字符串参数都必须
Map Map=newhashmap();
map.put(“methodName”,toRequestBody(methodName));
map.put(“userid”,toRequestBody(userid));
map.put(“关系”,即请求主体(关系));
map.put(“图标类型”,toRequestBody(图标类型));
map.put(“icon_id”,toRequestBody(iconId));
map.put(“名称”,toRequestBody(名称));
map.put(“relation_id”,toRequestBody(relationId));
//要放置图像文件,您必须执行以下操作
文件=新文件(“文件名”);
RequestBody fileBody=RequestBody.create(MediaType.parse(“image/png”),文件);
put(“相对图像\”文件名=\“某些文件\.png\”,文件体);
//此方法将字符串转换为RequestBody
公共静态RequestBody到RequestBody(字符串值){
RequestBody=RequestBody.create(MediaType.parse(“text/plain”),值);
返回体;
}
//发送您的请求
call=service.loadLevel1halfIconswithImage(描述,参数);
如果您不想使用PartMap,只需将其作为参数传递即可。请检查我的答案,以获得有关随请求发送图像文件的一些线索。简单地说,我是这样做的: 我已经改变了
Call<Result> resultCall = service.uploadImage(body);
并创建如下对象:
Result result = new Result();
result.setResult("success");
result.setValue("my value");
您可以根据需要更改类,然后在发送请求时传递对象。因此您的类将如下所示:
ApiService.java
/**
* @author Pratik Butani on 23/4/16.
*/
public interface ApiService {
/*
Retrofit get annotation with our URL
And our method that will return us the List of Contacts
*/
@Multipart
@POST("upload.php")
Call<Result> uploadImage(@Part MultipartBody.Part file, @Part("result") Result result);
}
/**
*@作者Pratik Butani,2016年4月23日。
*/
公共接口服务{
/*
用我们的URL改装get注释
我们的方法将返回联系人列表
*/
@多部分
@POST(“upload.php”)
调用uploadImage(@Part MultipartBody.Part文件,@Part(“result”)result);
}
我的PHP代码是:
<?php
$file_path = "";
$var = $_POST['result']; //here I m getting JSON
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
$result = array("result" => "success", "value" => $var);
} else{
$result = array("result" => "error");
}
echo json_encode($result);
?>
希望它能对您有所帮助。谢谢。我们可以在multipart body builder中添加指定类型的所有请求参数,如下面的一个图像文件。我已经设置了媒体类型parse
multipart/form data
和一些其他参数,我已经设置了媒体类型parsetext/plain
。这个生成器将构建成多部分body并可以通过在多部分正文中使用正文注释结束
@Multipart
@POST("user/update")
Call<ResponseBody> addDocument(@@Part MultipartBody file);
final MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
.setType(MultipartBody.FORM);
requestBodyBuilder.addFormDataPart("doc_image_file", imageFile.getName(),
RequestBody.create(MediaType.parse("multipart/form-data"), imageFile));
requestBodyBuilder.addFormDataPart("user_id", null, RequestBody.create(MediaType.parse("text/plain"),"12"));
requestBodyBuilder.addFormDataPart("doc_name", null, RequestBody.create(MediaType.parse("text/plain"),"myfile"));
requestBodyBuilder.addFormDataPart("doc_category", null, RequestBody.create(MediaType.parse("text/plain"),category));
requestBodyBuilder.addFormDataPart("doc_image_file", imageFile.getName(),RequestBody.create(MediaType.parse("multipart/form-data"),imageFile));
requestBodyBuilder.addFormDataPart("doc_text_content", null, RequestBody.create(MediaType.parse("text/plain"),body));
RequestBody multipartBody = requestBodyBuilder.build();
@Multipart
@发布(“用户/更新”)
调用addDocument(@@Part MultipartBody文件);
final MultipartBody.Builder requestBodyBuilder=新MultipartBody.Builder()
.setType(MultipartBody.FORM);
requestBodyBuilder.addFormDataPart(“doc\u image\u file”,imageFile.getName(),
create(MediaType.parse(“多部分/表单数据”),imageFile);
requestBodyBuilder.addFormDataPart(“user_id”,null,RequestBody.create(MediaType.parse(“text/plain”),“12”);
requestBodyBuilder.addFormDataPart(“doc_name”,null,RequestBody.create(MediaType.parse(“text/plain”),“myfile”);
requestBodyBuilder.addFormDataPart(“doc_category”,null,RequestBody.create(MediaType.parse(“text/plain”),category));
requestBodyBuilder.addFormDataPart(“doc_image_file”,imageFile.getName(),RequestBody.create(MediaType.parse(“多部分/表单数据”),imageFile));
requestBodyBuilder.addFormDataPart(“doc_text_content”,null,RequestBody.create(MediaType.parse(“text/plain”),body));
RequestBody multipartBody=requestBodyBuilder.build();
您还可以使用映射
和请求主体
作为值,字符串作为键来添加参数,您可以使用多部分和零件映射
发送此参数
检查以下代码,希望对您有所帮助:
@Multipart
@POST("/add")
Call<ResponseBody> addDocument(@PartMap Map<String,RequestBody> params);
Map<String, RequestBody> map = new HashMap<>();
map.put("user_id", RequestBody.create(MediaType.parse("multipart/form-data"), SessionManager.getInstance().getCurrentUserId()));
map.put("doc_name", RequestBody.create(MediaType.parse("multipart/form-data"), CommonUtils.removeExtension(textFile.getName())));
map.put("doc_category", RequestBody.create(MediaType.parse("multipart/form-data"), category));
map.put("doc_image_file", RequestBody.create(MediaType.parse("multipart/form-data"), imageFile));
map.put("doc_text_content", RequestBody.create(MediaType.parse("multipart/form-data"), body));
map.put("doc_update_time", RequestBody.create(MediaType.parse("multipart/form-data"), "" + new Date(textFile.lastModified())));
@Multipart
@职位(“/添加”)
调用addDocument(@PartMap-Map-params);
Map Map=newhashmap();
map.put(“user_id”,RequestBody.create(MediaType.parse(“multipart/formdata”),SessionManager.getInstance().getCurrentUserId());
map.put(“doc_name”、RequestBody.create(MediaType.parse(“多部分/表单数据”)、CommonUtils.removeExtension(textFile.getName());
map.put(“doc_category”,RequestBody.create(MediaType.parse(“multipart/formdata”),category);
map.put(“doc_image_file”,RequestBody.create(MediaType.parse(“multipart/formdata”),imageFile));
map.put(“doc_text_content”,RequestBody.create(MediaType.parse(“multipart/formdata”),body);
map.put(“doc\u update\u time”、RequestBody.create(MediaType.parse(“multipart/formdata”)、“”+新日期(textFile.lastModified());
只需遵循web浏览器执行多部分操作的方式。他们将嵌套键放入“[]”中,并为图像提供键
Call<SubmitLevel1Part2IconResp> loadLevel1halfIconswithImage(@Part("headerdata[relation][icon_type]") RequestBody icon_type, @Part("headerdata[relation][name]") RequestBody name, @Part MultipartBody.Part file);
以下是我的json请求格式:
{
“任务”:{
“类别id”:“1”,
“价格”:“10”,
“说明”:“1”,
“任务\u视频\u属性”:[
{
“链接”:“视频文件放在这里”,
“尺寸”:“100x100”
}
]
}
}
//我的要求变成
HashMap任务=新建HashMap();
task.put(“task[category_id]”,createPartFromString(categoryId));
task.put(“task[price]”,createPartFromString(“+etPrice.getText().toString());
task.put(“task[description]”,createPartFromString(“+etDescription.getText().toString());
//视频文件列表
最终列表体=新的ArrayList();
对于(int i=0;i<?php
$file_path = "";
$var = $_POST['result']; //here I m getting JSON
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
$result = array("result" => "success", "value" => $var);
} else{
$result = array("result" => "error");
}
echo json_encode($result);
?>
@Multipart
@POST("user/update")
Call<ResponseBody> addDocument(@@Part MultipartBody file);
final MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
.setType(MultipartBody.FORM);
requestBodyBuilder.addFormDataPart("doc_image_file", imageFile.getName(),
RequestBody.create(MediaType.parse("multipart/form-data"), imageFile));
requestBodyBuilder.addFormDataPart("user_id", null, RequestBody.create(MediaType.parse("text/plain"),"12"));
requestBodyBuilder.addFormDataPart("doc_name", null, RequestBody.create(MediaType.parse("text/plain"),"myfile"));
requestBodyBuilder.addFormDataPart("doc_category", null, RequestBody.create(MediaType.parse("text/plain"),category));
requestBodyBuilder.addFormDataPart("doc_image_file", imageFile.getName(),RequestBody.create(MediaType.parse("multipart/form-data"),imageFile));
requestBodyBuilder.addFormDataPart("doc_text_content", null, RequestBody.create(MediaType.parse("text/plain"),body));
RequestBody multipartBody = requestBodyBuilder.build();
@Multipart
@POST("/add")
Call<ResponseBody> addDocument(@PartMap Map<String,RequestBody> params);
Map<String, RequestBody> map = new HashMap<>();
map.put("user_id", RequestBody.create(MediaType.parse("multipart/form-data"), SessionManager.getInstance().getCurrentUserId()));
map.put("doc_name", RequestBody.create(MediaType.parse("multipart/form-data"), CommonUtils.removeExtension(textFile.getName())));
map.put("doc_category", RequestBody.create(MediaType.parse("multipart/form-data"), category));
map.put("doc_image_file", RequestBody.create(MediaType.parse("multipart/form-data"), imageFile));
map.put("doc_text_content", RequestBody.create(MediaType.parse("multipart/form-data"), body));
map.put("doc_update_time", RequestBody.create(MediaType.parse("multipart/form-data"), "" + new Date(textFile.lastModified())));
Call<SubmitLevel1Part2IconResp> loadLevel1halfIconswithImage(@Part("headerdata[relation][icon_type]") RequestBody icon_type, @Part("headerdata[relation][name]") RequestBody name, @Part MultipartBody.Part file);
// MultipartBody.Part is used to send also the actual filename
MultipartBody.Part body = MultipartBody.Part.createFormData("headerdata[relation][relative_image]", fileUpload.getName(), requestFile);
call = service.loadLevel1halfIconswithImage(icon_type, name, body);
Here is my json request format is :
{
"task":{
"category_id":"1",
"price":"10",
"description":"1",
"task_videos_attributes":[
{
"link":"video file goes here",
"size":"100x100"
}
]
}
}
// my request becomes
HashMap<String, RequestBody> task = new HashMap();
task.put("task[category_id]", createPartFromString(categoryId));
task.put("task[price]", createPartFromString("" + etPrice.getText().toString()));
task.put("task[description]", createPartFromString("" + etDescription.getText().toString()));
// for videos file list
final List<MultipartBody.Part> body = new ArrayList<>();
for (int i = 0; i < videos.size(); i++) {
task.put("task[task_videos_attributes][" + i+ "][size]", createPartFromString("100x100"));
File videoFile = new File(videos.get(i));
RequestBody requestBody = RequestBody.create(MediaType.parse("video/mp4"), videoFile);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("task[task_videos_attributes][" + i + "][link]", videoFile.getName(), requestBody);
body.add(fileToUpload);
}
// here is a final call
new RestClient(this).getInstance().get().postTask(body, task).enqueue(callback);
// This function converts my string to request body
@NonNull
private RequestBody createPartFromString(String descriptionString) {
if (descriptionString == null)
return RequestBody.create(MultipartBody.FORM, "");
return RequestBody.create(
MultipartBody.FORM, descriptionString);
}
public interface ApiService {
@POST("/event/store")
Call<ResModel> event_store(@Body RequestBody file);
}
public class ApiClient {
public static final String API_BASE_URL = "api base url";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static Retrofit.Builder builder = new Retrofit.Builder().baseUrl(API_BASE_URL).addConverterFactory(GsonConverterFactory.create());
public static ApiService createService(Class<ApiService> serviceClass)
{
Retrofit retrofit = builder.client(httpClient.build()).build();
return retrofit.create(serviceClass);
}
}
ApiService service = ApiClient.createService(ApiService.class);
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
builder.addFormDataPart("event_name", "xyz");
builder.addFormDataPart("desc", "Lorem ipsum");
// Single Image
builder.addFormDataPart("files",file1.getName(),RequestBody.create(MediaType.parse("image/*"), file1));
// Multiple Images
for (int i = 0; i <filePaths.size() ; i++) {
File file = new File(filePaths.get(i));
RequestBody requestImage = RequestBody.create(MediaType.parse("multipart/form-data"), file);
builder.addFormDataPart("event_images[]", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
}
MultipartBody requestBody = builder.build();
Call<ResModel> call = service.event_store(requestBody);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Toast.makeText(getBaseContext(),"All fine",Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getBaseContext(),t.getMessage(),Toast.LENGTH_SHORT).show();
}
});
MultipartBody.Part Partname = MultipartBody.Part.createFormData("ParamName", "Value");
@Multipart
@POST("api/service/uploadVideo")
Call<ResponseBody> uploadVideoToServer(
@Part MultipartBody.Part video,
@Part MultipartBody.Part param2,
@Part MultipartBody.Part param3 ....
);