文章标题

来源:互联网 发布:每天目标的软件 编辑:程序博客网 时间:2024/05/22 13:21

Retrofit 2.0使用(2)如何使用@Body的形式发送Post

  • 在使用Retrofit的时候如果只是有几个参数我们可以用@Querry的形式,然后需要使用’,’隔开
    但是在需要@Querry的参数多了之后,如果再用上面的方式就会造成参数写了一大堆的麻烦事 所以Retrofit就提供了@Body
    的形式来帮助我们处理这种事务

下面看代码吧

方法1:

public interface LoginApiService {    @Headers({"Content-Type: application/json"})    @POST("server?")    Observable<GetLoginJson> Login(@Body RequestBody body);}

  • Content-Type 表示请求信息的格式,这个在Spring MVC里有应用 然后application/json
    就代表json数据格式,当然还有很多其他的格式,这个有兴趣可以去查阅一下

方法2:

private static OkHttpClient okHttpClient = new OkHttpClient.Builder()            /*            * 这里可以添加一个HttpLoggingInterceptor,因为Retrofit封装好了从Http请求到解析,            出了bug很难找出来问题,添加HttpLoggingInterceptor拦截器方便调试接口            * */            .addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {                @Override                public void log(String message) {                    Logger.e(message);                }            }))            .addInterceptor(new Interceptor() {                @Override                public Response intercept(Chain chain) throws IOException {                    Request.Builder  requestBuilder=chain.request().newBuilder();                    requestBuilder.addHeader("Content-Type","application/json");//添加头文件,Content-Type 表示请求信息的格式,然后application/json  就代表json数据格式                    return chain.proceed(requestBuilder.build());                }            })            .connectTimeout(30, TimeUnit.SECONDS)            .readTimeout(30,TimeUnit.SECONDS)            .build();private static Retrofit retrofit=new Retrofit.Builder()            .baseUrl(URLs.URL_API_HOST)            .client(okHttpClient)            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())            .addConverterFactory(FastJsonConverterFactory.create())            .build();
  • 然后你需要做的是封装一个Post请求的类
    public class PostInfo {    private PostInfoBean postInfoBean;    public PostInfoBean getPostInfoBean() {        return postInfoBean;    }    public void setPostInfoBean(PostInfoBean postInfoBean) {        this.postInfoBean = postInfoBean;    }    //获取json数据,运用了fastJson框架    public static String getJson(PostInfo postInfo){        String json= JSON.toJSONString(postInfo);        Logger.d(json);        return json;    }    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);        String json = PostInfo.getJson(postInfo);        RequestBody body = RequestBody.create(MediaType.parse("application/json"),json);       loginApiService.Login(body);
原创粉丝点击