Retrofit简介

3 篇文章 0 订阅
1 篇文章 0 订阅

Retrofit

Retrofit

Retrofit 是Square的一个开源网络访问工具类;这里结合官方文档来介绍一下他的具体使用。官方文档地址

导入Retrofit 到Android Studio项目中去

在项目中的app Mudel中的build.Gradle文件中添加依赖:

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

加载之后就可以使用Retrofit了。

Retrofit的使用

  • 创建一个接口将网络访问的API写在里面,这个接口的命名按照官方文档的格式后缀一Service结尾;

    public interface HttpService{
        @GET("/")
        Call<String> getBaidu();
    
    }
    
  • 创建Retrofit实例,代码如下:

    Retrofit retrofit =new Retrofit.Builder()  //返回Retrofit对象
                                .baseUrl("http://www.baidu.com/")//设置根地址
                                .addConverterFactory(GsonConverterFactory.create())//解析拿到的数据
                                .build();//完成创建
    

    注意baseUrl必须是一“/”结尾否则要报错。

  • 利用Retrofit实例闯将一个实现了步骤1的接口的文档;通过service调用相应的方法得到一个Call对象。

    HttpService service = retrofit.create(HttpService.class);
    Call<String> baidu = service.getBaidu();
    
  • 然后同步或异步的执行Call对象访问网络;


Call instances can be executed either synchronously or asynchronously. Each instance can only be used once, but calling clone() will create a new instance that can be used.

以上是官方文档对Call对象的一段描述,其大概意思是Call对象能同步或异步的发起网络请求但是每个对象只能发起一次请求,可以通过clone()方法创建新的实例继续发起请求。

备注:以下是Square提供的常用数据解析裤:

  • Gson: com.squareup.retrofit2:converter-gson
  • Jackson: com.squareup.retrofit2:converter-jackson
  • Moshi: com.squareup.retrofit2:converter-moshi
  • Protobuf: com.squareup.retrofit2:converter-protobuf
  • Wire: com.squareup.retrofit2:converter-wire
  • Simple XML: com.squareup.retrofit2:converter-simplexml
  • Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值