Retrofit

作者: 今天也要努力呀y | 来源:发表于2019-07-20 19:23 被阅读0次

参考https://www.jianshu.com/p/0fda3132cf98

简介:
一个网络加载框架,底层使用Ohttp封装的,网络请求的工作本质由okhttp完成,retrofit仅负责请求接口的封装
好处:
可以配置不同的HttpClient,如Okhttp,HttpClient
支持同步,异步和Rxjava
可以配置不同的反序列化(从字节流创建对象)工具来解析数据,如json,xml
请求速度快,方便
使用方法:

dependencies {
    // Okhttp库
    compile 'com.squareup.okhttp3:okhttp:3.1.2'
    // Retrofit库
    compile 'com.squareup.retrofit2:retrofit:2.0.2'
}
<uses-permission android:name="android.permission.INTERNET"/>

创建接收服务器返回数据的类

public class News {
    // 根据返回数据的格式和数据解析方式(Json、XML等)定义
    ...
}

创建用于网络请求的接口

public interface APi {
    // @GET注解的作用:采用Get方法发送网络请求
    // getNews(...) = 接收网络请求数据的方法
    // 其中返回类型为Call<News>,News是接收数据的类(即上面定义的News类)
    // 如果想直接获得Responsebody中的内容,可以定义网络请求返回值为Call<ResponseBody>
    @Headers("apikey:81bf9da930c7f9825a3c3383f1d8d766")
    @GET("word/word")
    Call<News> getNews(@Query("num") String num,@Query("page")String page);
}
Retrofit retrofit = new Retrofit.Builder()
        //设置数据解析器
        .addConverterFactory(GsonConverterFactory.create())
        //设置网络请求的Url地址
        .baseUrl("http://apis.baidu.com/txapi/")
        .build();
// 创建网络请求接口的实例
mApi = retrofit.create(APi.class);

注解代码 请求格式
@GET GET请求
@POST POST请求
@DELETE DELETE请求
@HEAD HEAD请求
@OPTIONS OPTIONS请求
@PATCH PATCH请求

Retrofit的GET请求
有一行代码:
baseUrl("http://apis.baidu.com/txapi/")

这个http://apis.baidu.com/txapi/是我们要访问的接口的BaseUrl,
①用GET注解的字符串 "word/word"会追加到BaseUrl中变为:http://apis.baidu.com/txapi/word/word
②?num=10&page=1用query注释,@Query("num") String num,@Query("page")String page
③不带?分隔符),那就不用Query注解了,而是使用Path注解
首先都是定义一个API接口

相关文章

网友评论

      本文标题:Retrofit

      本文链接:https://www.haomeiwen.com/subject/xbwylctx.html