之前做了几个项目,网络请求使用的是默认数据格式,一试就通,就没有探究过其中的原理。这次更换了数据格式,一堆问题······
封装的默认格式:Content-Type:application/json; charset=utf-8
新的需求:Content-Type:application/x-www-form-urlencoded; charset=utf-8
之前的网络请求接口这样写:
public interface LoginService{
@POST("login/")
Call<ResponseBody> login(@Body UserBean user);
}
············
Call<ResponseBody> call = retrofit.create(LoginService.class).login(user);
可以直接传一个UserBean,传到服务端的就是个json数据:{"user":"user"}
沿用这种方法,在生成Content-Type:application/x-www-form-urlencoded; charset=utf-8
数据时,传到服务端的数据变成了:{"{"user":"user"}":null}
,就是将整个json数据作为key
,而value
为空。
翻了一堆网页,终于发现,应该使用表单数据(@Field
),而不是@Body
。
如下:
public interface LoginService{
@FormUrlEncoded
@Headers({"Content-Type:application/x-www-form-urlencoded; charset=utf-8"})
@POST("login/")
Call<ResponseBody> login(@Field("user") String user);
}
············
Call<ResponseBody> call = retrofit.create(LoginService.class).login(user);
当有多个表单数据时,使用@FieldMap
:
public interface LoginService{
@FormUrlEncoded
@Headers({"Content-Type:application/x-www-form-urlencoded; charset=utf-8"})
@POST("login/")
Call<ResponseBody> login(@FieldMap Map<String, String> map);
}
············
Map<String, String> params = new ArrayMap<>()
params.put("username", "zhangsan");
params.put("password", "123456");
Call<ResponseBody> call = retrofit.create(LoginService.class).login(params);
Retrofit2学习:搞定 Android Retrofit2 常用请求
github:https://github.com/square/retrofit