retorifit post请求 FieldMap 导致int变为float
时间: 2023-07-01 15:28:21 浏览: 50
在使用Retrofit进行POST请求时,如果使用了@FieldMap注解,那么Retrofit会默认使用application/x-www-form-urlencoded的方式将参数转为字符串,并在请求体中发送。由于这种方式只支持字符串类型,因此在传递整型参数时,可能会被转为浮点型。如果要保持整型参数的类型,可以使用@Query注解或者将参数转换为字符串类型再传递。
以下是使用@Query注解的示例:
```java
@FormUrlEncoded
@POST("user")
Call<User> createUser(@Field("name") String name, @Query("age") int age);
```
如果要使用@FieldMap注解,可以将整型参数转换为字符串类型再传递,如下所示:
```java
@FormUrlEncoded
@POST("user")
Call<User> createUser(@FieldMap Map<String, String> fields);
// example
Map<String, String> fields = new HashMap<>();
fields.put("name", "John");
fields.put("age", String.valueOf(30));
Call<User> call = apiService.createUser(fields);
```
在上面的例子中,使用了一个Map来存储参数。将整型的age参数转换为字符串类型后,再将其放入Map中传递。这样就可以避免整型参数被转换为浮点型的问题了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)