Retrofit 2 - 使用Body对象发布FieldMap

时间:2017-02-13 04:56:59

标签: android retrofit retrofit2

我想使用Retrofit发布HashMap和Object。 我在下面尝试了此代码,但收到了IllegalArgumentException

@POST("update")
Call<RSP010> postApi010(@FieldMap HashMap<String, String> defaultData, @Body User user);

logcat的

java.lang.IllegalArgumentException: @FieldMap parameters can only be used with form encoding. (parameter #1)

但是当我添加@FormUrlEncoded时。它说

java.lang.IllegalArgumentException: @Body parameters cannot be used with form or multi-part encoding. (parameter #2)

更新代码

public static HashMap<String, String> defaultData(){
    HashMap<String, String> map = new HashMap<>();
    map.put("last_get_time", String.valueOf(SharedPreferencesHelper.getLongValue(AppConstants.LAST_GET_UPDATE)));
    map.put("duid", SharedPreferencesHelper.getStringValue(AppConstants.DUID));
    return map;

我要发布的我的对象

int profile_id;
private String name;
private String name_kana; // あいうえお
private int gender; // 1 nam 2 nu
private String birth_day;
private String birth_time;
private String birth_place;
private String relationship;

说明:

我想通过API将多个变量发布到服务器。我希望在每个API中使用的默认变量FieldMap defaultData

https://futurestud.io/tutorials/retrofit-send-objects-in-request-body我已经读过这篇文章了,它说不是张贴对象的所有单独变量,而是直接发布对象。

2 个答案:

答案 0 :(得分:3)

您可以@Body User user发送@FieldMap HashMap<String, String> defaultData

    String user = new Gson().toJson(user);
    HashMap<String, String> map = new HashMap<>();
    map.put("last_get_time", String.valueOf(SharedPreferencesHelper.getLongValue(AppConstants.LAST_GET_UPDATE)));
    map.put("duid", SharedPreferencesHelper.getStringValue(AppConstants.DUID));
    map.put("duid", SharedPreferencesHelper.getStringValue(AppConstants.DUID));
    map.put("user", user);

使用@PartMap Map<String, RequestBody>

@Multipart
@POST("update")
Call<RSP010> postApi010(@PartMap Map<String, RequestBody> defaultData);

并创建您的请求参数

Map<String, RequestBody> map = new HashMap<>();
map.put("last_get_time", toRequestBody(String.valueOf(SharedPreferencesHelper.getLongValue(AppConstants.LAST_GET_UPDATE))));
map.put("duid", toRequestBody(SharedPreferencesHelper.getStringValue(AppConstants.DUID)));
RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),new Gson().toJson(user));
map.put("user", body);

// This method  converts String to RequestBody
public static RequestBody toRequestBody (String value) {
     RequestBody body = RequestBody.create(MediaType.parse("text/plain"), value);
     return body ;
}

答案 1 :(得分:1)

将您的方法修改为:

@POST("update")
Call<RSP010> postApi010(@Query("last_get_time") String lastGetTime, @Query("duid") String uid, @Body User user);