我想使用 Retrofit 发布一个 HashMap 和一个对象。
我在下面尝试了这段代码,但收到了 IllegalArgumentException
。
@POST("update")
Call<RSP010> postApi010(@FieldMap HashMap<String, String> defaultData, @Body User user);
日志
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 将多个变量发布到服务器。 FieldMap defaultData
用于我想在每个 API 中使用的默认变量。
https://futurestud.io/tutorials/retrofit-send-objects-in-request-body我读过这个,它说我可以直接发布一个对象,而不是发布一个对象的所有单独变量。
最佳答案
您可以发送@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 ;
}
关于android - Retrofit 2 - 使用 Body 对象发布 FieldMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42196910/