gpt4 book ai didi

android - 如何使用 retrofit 2 一起发送文件和其他参数

转载 作者:太空宇宙 更新时间:2023-11-03 12:15:18 24 4
gpt4 key购买 nike

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

我必须发送服务器 JSON

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

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

如果文件是一个字符串,我知道如何处理它。如果文件是文件对象,我不知道该怎么做。

最佳答案

使用 gson 并为该位置创建一个模型类。

将以下依赖项添加到您的build.gradle

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

创建一个模型来表示位置。

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

例如:

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接口(interface)。

public interface Api {

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

}

创建一个Retrofit实例并调用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() 调用。

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

让我知道这是否有效。显然我没有机会在您的确切场景中进行测试,但我相当有信心这应该有效。我不是 100% 的唯一部分是 @Part("location") Location location 是否应该是 @Body("location") Location location

关于android - 如何使用 retrofit 2 一起发送文件和其他参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40008840/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com