Android-->Retrofit 2.0 beta2 使用方法

1.首先

   compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'

2.声明接口

  public interface GetBaidu{
      @GET("http://www.baidu.com/")
      Call<ResponseBody> get();
    //Call<T> get();//必须是这种形式,这是2.0之后的新形式
//我这里需要返回网页内容,不需要转换成Json数据,所以用了ResponseBody;
//你也可以使用Call<GsonBean> get();这样的话,需要添加Gson转换器...后续介绍
  }

3.调用接口

//经过测试: baseUrl必须设置,如果 声明接口时@GET使用了完整的url路径,那么baseUrl就会被忽略,否则就是拼接url
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.baidu.com/").build();//在这里可以添加 Gson转换器等;
  GetBaidu getBaidu = retrofit.create(GetBaidu.class);//使用上面声明的接口创建
  Call<ResponseBody> call = getBaidu.get();//获取一个Call,才可以执行请求

//同步请求....
  try {
      Response<ResponseBody> bodyResponse = call.execute();
      String body = bodyResponse.body().string();//获取返回体的字符串
      Log.e(TAG, "");
  } catch (IOException e) {
      e.printStackTrace();
  }

//异步请求....
  call.enqueue(new Callback<ResponseBody>() {//异步
      @Override
      public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
          try {
              String body = response.body().string();//获取返回体的字符串
          } catch (IOException e) {
              e.printStackTrace();
          }
          Log.e(TAG, "");
      }

      @Override
      public void onFailure(Throwable t) {
          Log.e(TAG, "");
      }
  });

未完待续….

参考文章:
http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0915/3460.html

至此: 文章就结束了,如有疑问: QQ群:274306954 欢迎您的加入.

你可能感兴趣的:(retrofit,2-0beta2)