gpt4 book ai didi

android - Retrofit2 多部分上传图像和其他数据

转载 作者:行者123 更新时间:2023-11-29 16:39:48 25 4
gpt4 key购买 nike

ApiServices apiServices = 
RetrofitInstance.getRetrofitInstance().create(ApiServices.class);
MultipartBody.Part body = null;
File file = new File(mFilePath);
RequestBody data = RequestBody.create(MediaType.parse(“image/*“), file);

body = MultipartBody.Part.createFormData(“image”, file.getName(), data);
RequestBody description =
RequestBody.create(MediaType.parse(“text/plain”),“Hello multipart”);
RequestBody sports_id = RequestBody.create(MediaType.parse(“text/plain”),“2”);
RequestBody location = RequestBody.create(MediaType.parse(“text/plain”), “New Delhi”);
String auth_token = ((MainActivity)getActivity()).appSharedPreference.getAuthToken() ;

Call<JsonElement> call = apiservices.postMoment(auth_token , description, sports_id, location, body) ;
call.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(retrofit2.Call<JsonElement> call, Response<JsonElement> response) {
Log.e(TAG , “response: “+response.toString());
}

@Override
public void onFailure(retrofit2.Call<JsonElement> call, Throwable t) {
Log.e(TAG , “error: “+t.getMessage());
}
});

API接口(interface):

@Multipart
@POST("/moments")
Call<JsonElement> postMoment(
@Header("X-User-Token")String access_token,
@Part("description") RequestBody description,
@Part("sport_id") RequestBody sport_id,
@Part("location") RequestBody location
@Part MultipartBody.Part image,

);

但是,我要如何将所有这些参数封装到一个“时刻”中。就像我们在创建 Json 对象时所做的那样

{
moment : 

{ “description” : “<Description string>” ,
“sports_id”: “<sports_id>” ,
“location”: “<location>”
“image”:”<image>”
}

我对api接口(interface)的请求应该是这样的:

Call<JsonElement> call = apiservices.postMoment(auth_token, single_parameter) ;

在那个单一的参数中,所有的字段都被封装了。我试过 Map 但无法将整个数据组合成一个名为“moment”的字符串。

如有任何帮助,我们将不胜感激。谢谢

最佳答案

请试试这个,你可以为你的请求创建 pojo 类

@POST("/moments")
Call<JsonElement> postMoment(
@Header("X-User-Token")String access_token,
@Body RequestMoment moment,
);

界面

public class RequestMoment {
public Moment moment;
public class Moment {
public Moment(RequestBody description, RequestBody sport_id,
RequestBody location, MultipartBody.Part image){
this.description = description;
this.sport_id = sport_id;
this.location = location;
this.image = image;
}
public RequestBody description;
public RequestBody sport_id;
public RequestBody location;
public MultipartBody.Part image;
}
}

API调用

Moment moment = new Moment(description, sports_id, location, body);
Call<JsonElement> call = apiservices.postMoment(auth_token, moment);

关于android - Retrofit2 多部分上传图像和其他数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51242625/

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