Adm*_*kka 2 android retrofit retrofit2
我想使用 Retrofit 发布一个 HashMap 和一个对象。我在下面尝试了此代码,但收到了IllegalArgumentException.
@POST("update")
Call<RSP010> postApi010(@FieldMap HashMap<String, String> defaultData, @Body User user);
Run Code Online (Sandbox Code Playgroud)
逻辑猫
java.lang.IllegalArgumentException: @FieldMap parameters can only be used with form encoding. (parameter #1)
Run Code Online (Sandbox Code Playgroud)
但是当我添加@FormUrlEncoded. 它说
java.lang.IllegalArgumentException: @Body parameters cannot be used with form or multi-part encoding. (parameter #2)
Run Code Online (Sandbox Code Playgroud)
更新代码
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;
Run Code Online (Sandbox Code Playgroud)
我要发布的对象
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;
Run Code Online (Sandbox Code Playgroud)
解释:
我想通过 API 将多个变量发布到服务器。defaultData我想在每个 API 中使用的默认变量的FieldMap 。
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);
Run Code Online (Sandbox Code Playgroud)
或者
用 @PartMap Map<String, RequestBody>
@Multipart
@POST("update")
Call<RSP010> postApi010(@PartMap Map<String, RequestBody> defaultData);
Run Code Online (Sandbox Code Playgroud)
并创建您的请求参数
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 ;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9646 次 |
| 最近记录: |