Retrofit的使用

来源:互联网 发布:淘宝皇冠账号多少钱 编辑:程序博客网 时间:2024/06/08 09:35

Retrofit是一款很有创意的开源网络框架,因为其简单与出色的性能,Retrofit 是安卓上最流行的且很有创意的开源网络框架之一。,Square公司为Android开源的类型安全的Http客户端;底层基于OkHttp,使用OkHttp客户端;让用户自定义接口,将java API的定义转换为interface形式;使用注解对接口进行解析和调用;支持配置json解析器;Retrofit源码下载地址:https://github.com/square/retrofit

1.添加依赖

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

2.创建Retrofit实例对象

 Retrofit retrofit = new Retrofit.Builder().           //设置服务器主机  服务器主机应该以/结束, 否则会报错           baseUrl("http://192.168.31.101:8080/apitest/")           //配置Gson最为json的解析器          .addConverterFactory(GsonConverterFactory.create())          .build();

3.定义业务逻辑接口

 public interface StuApi {    //使用GET定义一个业务方法,获取类表信息    @GET("test")    Call<User> getOrder(); }

4 创建接口实例对象

 stuApi = retrofit.create(StuApi.class);

5.获取业务方法的调用对象,并进行请求

//调用接口的 方法获取call对象,此时只是获取了http请求信息的封装独享,就是Call对象        //当时此时还未执行http请求        Call<User> useOrder = stuApi.getOrder();        /**Response<User> response = useOrder.execute();        User user = response.body();        tv.setText(user.nickname);        //以上的代码会阻塞UI线程,因此不能在安卓的主线程中调用,不然会面临NetworkOnMainThreadException。如果你想调用execute方法,请在后台线程执行。**/        //异步执行业务方法        useOrder.enqueue(new Callback<User>() {            @Override            public void onResponse(Call<User> call, Response<User> response) {                //response就是响应结果的封装对象                User body = response.body();                tv.setText(body.nickname+body.gender);            }            @Override            public void onFailure(Call<User> call, Throwable t) {                tv.setText(t.getMessage());            }        });    }

6.使用POST注解

  //使用POST注解,进行post请求,登录的接口,提交key-value数据    @FormUrlEncoded //如果没有这句会报错@Field parameters can only be used with form encoding    @POST("login")    Call<People> login(@Field("username")String p1,@Field("password")String p2);
0 0
原创粉丝点击