用@multipart改造@body有问题

Vis*_*tel 8 android annotations retrofit2

图像类型为对象的类型.

案例1.(我做过的)

服务参数:

{"id":"1","name":"vishal","image/file":""} 
Run Code Online (Sandbox Code Playgroud)

那时我APIRetrofit

@Multipart
@POST("webservice")
Call<SignUpResp> loadSignupMultipart(@Part("description") RequestBody description, @Part MultipartBody.Part file, @QueryMap HashMap<String, String> params);
Run Code Online (Sandbox Code Playgroud)

案例2.(我遇到问题) @Body class<UploadwithImage>

{
    "methodName":"submitLevel1Part2Icon",
    "userid":"150",
    "headerData":{
        "fiction":{
            "icon_type":"1",
            "icon_id":"3"},
        "nonfiction":{
            "icon_type":"2",
            "icon_id":"4"},
        "relation":{
            "icon_type":"3",
            "icon_id":"0",
            "name":"Ronak",
            "relative_image":"<File>",
            "relation_id":"3"},
        "self":{
            "icon_type":"4",
            "icon_id":"0"}
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试这个 API

 @Multipart
 @POST("webservice")
 Call<SubmitLevel1Part2IconResp> loadLevel1halfIconswithImage(@Part("description") RequestBody description, @Part MultipartBody.Part file, @Body UploadwithImage uploadImage);
Run Code Online (Sandbox Code Playgroud)

Java方面

    /**
     * code for multipart
     */
     // create RequestBody instance from file
     RequestBody requestFile =  RequestBody.create(MediaType.parse("multipart/form-data"), fileUpload);

     // MultipartBody.Part is used to send also the actual filename
     MultipartBody.Part body =  MultipartBody.Part.createFormData("methodName[headerData][relation][relative_image]", fileUpload.getName(), requestFile);

     // add another part within the multipart request
     String descriptionString = "hello, this is description speaking";
     RequestBody description = RequestBody.create(MediaType.parse("multipart/form-data"), descriptionString);

    call = service.loadLevel1halfIconswithImage(description, body, levelOneHalfIcons);
Run Code Online (Sandbox Code Playgroud)

我不知道为什么,但它返回错误,如:

"@Body参数不能与表单或多部分编码一起使用"

任何帮助,将不胜感激.

Ank*_*wal 9

将您的方法更改为

@Multipart
@POST("users/{id}/user_photos")
Call<models.UploadResponse> uploadPhoto(@Path("id") int userId, @PartMap Map<String, RequestBody> params);
Run Code Online (Sandbox Code Playgroud)

现在创建您的请求参数,

//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);
Run Code Online (Sandbox Code Playgroud)

如果您不想使用PartMap,只需将它们作为参数传递即可.检查我的答案/sf/answers/2593678391/,以获得有关发送带有请求的图像文件的线索.


Pra*_*ani 9

简单来说,我这样做了:

我通过改变进行了测试

Call<Result> resultCall = service.uploadImage(body); 
Run Code Online (Sandbox Code Playgroud)

Call<Result> resultCall = service.uploadImage(body, result);其中,结果

我的API的Result.java类(Response):

public class Result {

    @SerializedName("result")
    @Expose
    private String result;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @SerializedName("value")
    @Expose
    private String value;

    /**
     * @return The result
     */
    public String getResult() {
        return result;
    }

    /**
     * @param result The result
     */
    public void setResult(String result) {
        this.result = result;
    }

}
Run Code Online (Sandbox Code Playgroud)

并创建了如下对象:

Result result = new Result();
result.setResult("success");
result.setValue("my value");
Run Code Online (Sandbox Code Playgroud)

您可以根据需要更改类,然后在发送请求时传递对象.所以你的ApiService类就像:

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);

}
Run Code Online (Sandbox Code Playgroud)

和我的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);

?>
Run Code Online (Sandbox Code Playgroud)

希望它能帮到你.谢谢.

  • 谢谢你,这是处理这种情况的一种非常好的方法.+1 (2认同)

小智 7

您还可以使用Mapwith RequestBodyas value 和 string 作为键来添加参数,您可以使用 Multipart 和PartMap.

检查以下代码,希望它会有所帮助:

@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())));
Run Code Online (Sandbox Code Playgroud)


小智 5

我们可以在多部分主体构建器中添加具有指定类型的所有请求参数,如下面的一个图像文件。我已经设置了媒体类型解析multipart/form-data和其他一些参数我已经设置了媒体类型解析text/plain。该构建器将构建多部分正文,并且可以通过在多部分正文中使用正文注释进行发送。

@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();
Run Code Online (Sandbox Code Playgroud)