在使用Retrofit的时候若是只是有几个参数咱们能够用@Querry的形式,而后须要使用','隔开git
可是在须要@Querry的参数多了以后,若是再用上面的方式就会形成参数写了一大堆的麻烦事github
因此Retrofit就提供了@Body 的形式来帮助咱们处理这种事务json
下面看代码吧服务器
public interface LoginApiService { @Headers({"Content-Type: application/json","Accept: application/json"}) @POST("server?") Observable<GetLoginJson> Login(@Body RequestBody body); }
这是他的API接口,须要在开头@Header 而后后面的值。。。。。( ▼-▼ )!讲道理我如今还没弄明白为啥这样写,有啥规律可循,后面搞懂了再来补上app
补上:!post
Content-Type 表示请求信息的格式,这个在Spring MVC里有应用
而后application/json 就表明json数据格式,固然还有不少其余的格式,这个有兴趣能够去查阅一下
/***20161125修改**/this
无心间在简书上找到了@Header和@Headers的说明spa
@Header:header处理,不能被互相覆盖,用于修饰参数,code
//动态设置Header值 @GET("user") Call<User> getUser(@Header("Authorization") String authorization)
@Headers 用于修饰方法,用于设置多个Header值:server
@Headers({ "Accept: application/vnd.github.v3.full+json", "User-Agent: Retrofit-Sample-App" }) @GET("users/{username}") Call<User> getUser(@Path("username") String username);
。。。。。( ▼-▼ )!表示仍是不懂Headers的写法啊
引用自简书做者@BoBoMEe
/***20161125编辑 end**/
而后你须要作的是封装一个Post请求的类
public class PostInfo { private PostInfoBean postInfoBean; public PostInfoBean getPostInfoBean() { return postInfoBean; } public void setPostInfoBean(PostInfoBean postInfoBean) { this.postInfoBean = postInfoBean; } public class PostInfoBean{ private String command; private String posModel; private String posSn; private String posMac; private String userId; private String passWord; /**get 省略*/ /**set 省略*/ }
而后使用Retrofit的时候在你实例了ApiService那个接口以后,还须要实例化一个请求Header
实例化完成以后因为我这边服务器接收的是Json类型的请求,我还须要用Gson将他转成Json字符串的形式,而后再(很重要)经过RequestBody(包含于Okhttp包中)类转化为RequestBody,以后再调用API接口便可
LoginApiService loginApiService = mRetrofit.create(LoginApiService.class); PostInfo postInfo = new PostInfo(); PostInfo.PostInfoBean postInfoBean = postInfo.new PostInfoBean(); postInfoBean.setCommand("xxx"); postInfoBean.setPosModel("xx"); postInfoBean.setPosSn(getPhoneSn()); postInfoBean.setPosMac(getPhoneMac()); postInfoBean.setUserId("xx"); postInfoBean.setPassWord("xx"); postInfoBean.setVersion("xx"); postInfo.setPostInfoBean(postInfoBean); Gson gson = new Gson(); String postInfoStr = gson.toJson(postInfoBean); RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),postInfoStr); loginApiService.Login(body) .xxx.xxx;