Retrofit2.0网路框架

Retrofit是目前最流行的HTTP请求工具。

使用方法:

1.添加依赖:

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

2.定义一个接口,Retrofit会将该接口转换成为HTTP请求

public interface APIService{
    @GET("api/getUser")
     Call  getUserInfo();
}

3.发起HTTP请求,获取结果

//创建一个Retrofit客户端
  Retrofit retrofit = new Retrofit.Builder()
          .baseUrl("XXXXXXXXX")
          .build();

  //得到一个APIService代理对象
  APIService apiService = retrofit.create(APIService.class);
//生成一个HTTP请求
  Call userInfo = apiService.getUserInfo();
  //最后,就可以通过studentInfo对象获取WebServer内容
  //此处有两种请求方法:同步调用,异步调用
  //这里使用的是异步调用方法
  userInfo.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) {
            try {
                Log.i(TAG,response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call call, Throwable t) {
            Log.i(TAG, "onFailure: "+t);
        }
    });

进阶

上面方法获取到的是JSON数据,还要经过手动进一步解析才能获取所需内容,
而Retrofit默认只能解码HTTP bodies到 OkHttp's ResponseBody类型,要想使
Retrofit支持其他类型转换,必须通过Converters(数据转换器)转换。

1.添加Gson依赖:

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

2.创建User类

 public class User {

    @SerializedName("userId")
    @Expose
    private String userId;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("age")
    @Expose
    private int age;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return String.format("id:%s\nname:%s\nage:%d", userId, name, age);
    }
}

3.定义接口修改

public interface APIService{
    @GET("api/getUser")
     Call  getUserInfo();
}

4.发起HTTP请求修改

//创建一个Retrofit客户端
  Retrofit retrofit = new Retrofit.Builder()
          .baseUrl("XXXXXXXXXXX")
          //增加Gson转换
          .addConverterFactory(GsonConverterFactory.create())
          .build();

  //得到一个APIService代理对象
  APIService apiService = retrofit.create(APIService.class);
//生成一个HTTP请求
  Call userInfo = apiService.getUserInfo();
  userInfo.enqueue(new Callback() {
      @Override
      public void onResponse(Call call, Response response) {
          User user = response.body();
          Log.i(TAG, user.toString());
      }

      @Override
      public void onFailure(Call call, Throwable t) {
          Log.i(TAG, "onFailure: " + t);
      }
  });

你可能感兴趣的:(Retrofit2.0网路框架)