如何使用改造2一起发送文件和其他参数 [英] how to use retrofit 2 to send file and other params together

查看:66
本文介绍了如何使用改造2一起发送文件和其他参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个示例,如何将文件和其他参数一起发送到服务器.

I am looking for an example how could I send file and other params together to server.

我必须发送服务器JSON

I have to send server JSON which

{
    "title": "title",
    "file": "uploaded file instance",
    "location": {
        "lat": 48.8583,
        "lng": 2.29232,
        "place": "Eiffel Tower"
    }
}

我该如何创建Retrofit来处理这种情况?

How could I create Retrofit to handle this case?

如果file是一个字符串,我知道如何处理.如果file是File对象,我不知道该怎么做.

If file is a string I know how to handle this. If file is File object I have no idea how to do this.

推荐答案

使用 gson 并为该位置创建模型类.

Use gson and create a model class for the location.

在您的 build.gradle 中添加以下依赖项.

Add the following dependencies to your build.gradle.

compile 'com.squareup.retrofit2:converter-gson:2.0.0'
compile 'com.google.code.gson:gson:2.5'

创建一个表示位置的模型.

Create a model to represent the location.

public class Location {

    double lat;
    double lng;
    String location;

    public Location(double lat, double lon, String place) {
        this.lat = lat;
        this.lon = long;
        this.place = place;
    } 

}

如果有效负载字段的变量名与端点的实际所需名称不匹配,则需要添加注释 @SerializedName([expected name])

If the variable names for the payload fields don't match the actual required name for the endpoint you will need to add the annotation @SerializedName([expected name])

例如:

import com.google.gson.annotations.SerializedName;

public class Location {

    @SerializedName("lat")
    double latitude;
    @SerializedName("lng")
    double longitude;
    @SerializedName("place")
    String location;

    public Location(double lat, double lon, String place) {
        latitude = lat;
        longitude = long;
        location = place;
    } 

}

定义api接口.

public interface Api {

    @POST("upload/")
    @Multipart
    Call<ResponseBody> uploadFile(@Part("title") RequestBody title,
                                  @Part MultipartBody.Part imageFile,
                                  @Part("location") Location location
    );

}

创建一个 Retrofit 实例并调用api.

Create a Retrofit instance and call the api.

File file;
// create retrofit instance
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://baseurl.com/api/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();
// create api instance
Api api = retrofit.create(Api.class);
// create call object
Call<ResponseBody> uploadFileCall = api.uploadFile(
        RequestBody.create(MediaType.parse("text/plain"), "title"),
        MultipartBody.Part.createFormData(
            "file",
            file.getName(),
            RequestBody.create(MediaType.parse("image"), file)),
        new Location(48.8583, 2.29232, "Eiffel Tower"));
// sync call
try {
    ResponseBody responseBody = uploadFileCall.execute().body();
} catch (IOException e) {
    e.printStackTrace();
}
// async call
uploadFileCall.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        if (response.isSuccessful()) {
            // TODO
        }
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        // TODO
    }
});

如果不使用图像文件,则需要更改 MediaType.parse()调用.

You will need to change the MediaType.parse() call if you are not using an image file.

您可以类似地创建自定义响应类型对象,并用它替换 ResponseBody 以接收反序列化的结果对象.

You can similarly create a custom response type object and replace ResponseBody with it to receive a deserialized result object.

让我知道这是否可行.我显然没有机会在您的实际情况下进行测试,但我相当有信心这应该可行.我不是100%感兴趣的唯一部分是 @Part("location")位置位置是否应为 @Body("location")位置位置

Let me know if this works. I didn't have a chance to test in your exact scenario obviously but I'm fairly confident this should work. The only part I'm not 100% on is whether @Part("location") Location location should be @Body("location") Location location

这篇关于如何使用改造2一起发送文件和其他参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆