我正在寻找一个示例,如何将文件和其他参数一起发送到服务器。
我必须发送服务器JSON
{
"title": "title",
"file": "uploaded file instance",
"location": {
"lat": 48.8583,
"lng": 2.29232,
"place": "Eiffel Tower"
}
}
如何创建翻新来处理这种情况?
如果文件是一个字符串,我知道如何处理。如果文件是文件对象,我不知道该怎么做。
使用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接口。
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句