Retrofit
是最受开发者欢迎的一个网络请求库retrofit:2.5.0 - githubandroid
Retrofit
是Square公司开发的一款针对Android网络请求的框架,遵循Restful设计风格,底层基于OkHttp.dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
api 'com.squareup.retrofit2:converter-gson:2.0.2'
}
复制代码
<uses-permission android:name="android.permission.INTERNET"/>
复制代码
public class ResultData{
...
// 根据返回数据的格式和数据解析方式(Json、XML等)定义
}
复制代码
public interface GetRequestInterface {
@GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")
Call<ResultData> getCall();
// @GET注解的做用:采用Get方法发送网络请求
// getCall() = 接收网络请求数据的方法
// 其中返回类型为Call<*>,*是接收数据的类(即上面定义的Translation类)
// 若是想直接得到Responsebody中的内容,能够定义网络请求返回值为Call<ResponseBody>
}
复制代码
具体做用以及解释请自行前往官方文档查看,这里就不一一解释了git
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://fanyi.youdao.com/") // 设置网络请求的公共Url地址
.addConverterFactory(GsonConverterFactory.create()) // 设置数据解析器
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 支持RxJava平台
.build();
复制代码
数据解析器 Gradle依赖github
Gson com.squareup.retrofit2:converter-gson:2.0.2json
Simple XML com.squareup.retrofit2:converter-simplexml:2.0.2segmentfault
Protobuf com.squareup.retrofit2:converter-protobuf:2.0.2api
Wire com.squareup.retrofit2:converter-wire:2.0.2bash
网络请求适配器 Gradle依赖服务器
Java8 com.squareup.retrofit2:adapter-java8:2.0.2restful
// 建立 网络请求接口 的实例
GetRequestInterface request = retrofit.create(GetRequestInterface.class);
//对 发送请求 进行封装
Call<ResultData> call = request.getCall();
复制代码
/发送网络请求(异步)
call.enqueue(new Callback<ResultData>() {
//请求成功时回调
@Override
public void onResponse(Call<ResultData> call, Response<ResultData> response) {
//处理结果
}
//请求失败时候的回调
@Override
public void onFailure(Call<ResultData> call, Throwable throwable) {
//提示失败
}
});
// 发送网络请求(同步)
Response<ResultData> response = call.execute();
复制代码
//发送网络请求(异步)
call.enqueue(new Callback<ResultData>() {
//请求成功时回调
@Override
public void onResponse(Call<ResultData> call, Response<ResultData> response) {
// 对返回数据进行处理
response.body();//拿到ResultData对象进行数据操做
}
//请求失败时候的回调
@Override
public void onFailure(Call<ResultData> call, Throwable throwable) {
System.out.println("链接失败");
}
});
// 发送网络请求(同步)
Response<ResultData> response = call.execute();
// 对返回数据进行处理
response.body().blabla;
复制代码
关于Retrofit 2.5的简单介绍到这里就结束了,感谢阅读.
欢迎关注做者darryrzhong,更多干货等你来拿哟.
更多精彩文章请关注