Retrofit 进行单例封装,进行post 和get 请求

1,添加依赖

compile 'com.squareup.retrofit2:retrofit:2.1.0'

//依赖和retrofit对应的gson解析类库,配置了就拥有了json解析的功能

compile 'com.squareup.retrofit2:converter-gson:2.0.2'

 

2,Retrofit 创建对象进行单封装

  • 单例封装创建Retrofit对象

public class RetrofitHelper {

    private static RetrofitHelper mInstance = new RetrofitHelper();

    Retrofit retrofit;

    XiaoshuaiApi xiaoshuaiApi;

    private RetrofitHelper(){

        //1.创建Retrofit实例对象

        retrofit = new Retrofit.Builder()

                //设置服务器主机地址,要求url必须以/结尾

                .baseUrl("http://192.168.101.78:8080/apitest/")

                //使用Gson作为json数据的转换器

                .addConverterFactory(GsonConverterFactory.create())

                .build();





        //2.创建接口的实现类对象:让retrofit创建一个实例对象

        //Retrofit内部是通过动态代理来创建实例对象,并且监听对象方法的调用;

        //当我们调用业务方法时,Retrofit内部就获取方法的注解信息,这些信息

        //包含的请求方式,url,和请求参数等,于是它会自动的利用okhttp发送这些请求

        xiaoshuaiApi= retrofit.create(xiaoshuaiApi.class);





    }

    public static RetrofitHelper create(){

         return mInstance;

    }





    public XiaoshuaiApi getXiaoshuaiApi(){

        return xiaoshuaiApi;

    }

}
  • 调用对象post请求

private void post() {

    //3.得到请求的封装对象

    Call loginCall = RetrofitHelper.create()

                                         .getXiaoshuaiApi()

                                         .login("黎明","郭富城");

    //4.执行请求

    loginCall.enqueue(new Callback() {

        @Override

        public void onResponse(Call call, Response response) {

            User user = response.body();

            tvResult.setText(user.toString());

        }

        @Override

        public void onFailure(Call call, Throwable t) {





        }

    });

}
  • 调用 RetrofitHelper创建对象 。get请求

private void get() {

        //3.得到的是请求的封装对象,此时请求还没有执行呢,这个请求中封装了url和参数,

        //以及你期望解析的类型等

        Call stuCall = RetrofitHelper.create()

                                          .getXiaoshuaiApi()

                                          .getProductList();

        //4.执行请求

//        stuCall.execute();//同步执行请求

        stuCall.enqueue(new Callback() {

            @Override

            public void onResponse(Call call, Response response) {

                Stu stu = response.body();

                tvResult.setText("nickname:"+stu.nickname);

            }

            @Override

            public void onFailure(Call call, Throwable t) {

                tvResult.setText(t.getMessage());

            }

        });

    }

 

你可能感兴趣的:(Android)