对Retrofit的认识
Retrofit 是基于 OkHttp 封装的一套 RESTful(RESTful是一套api设计的风格) 网络请求框架
Retrofit是在okhttp基础之上做的封装,项目中可以直接用了。
Retrofit与Retrofit 2.0(二者分工协作)的区别:
Retrofit是一个RESTful的HTTP网络请求框架的封装,专注于接口的封装。
Retrofit 2.0 开始内置 OkHttp,专注于网络请求的高效。
通过Retrofit请求网络的原理:使用 Retrofit 接口层封装请求参数、Header、Url 等信息,之后由 OkHttp 完成后续的请求操作,在服务端返回数据之后,OkHttp 将原始的结果交给 Retrofit,后者根据用户的需求对结果进行解析。
Retrofit 是一个 RESTful 的 HTTP 网络请求框架的封装,网络请求的工作本质上是 OkHttp 完成,而 Retrofit 仅负责 网络请求接口的封装。
Retrofit框架网络请求流程图:
一、与安卓集成
- 添加依赖(在build.gradle文件中添加依赖)
build.gradle下添加:其中第一个为添加retrofit,第二及第三个为添加json解析,这里采用的是GSON
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
implementation 'com.google.code.gson:gson:2.7'
implementation 'com.squareup.okhttp3:okhttp:3.2.0'
- 加入 OkHttp 配置
// 创建 OKHttpClient
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(1000*60, TimeUnit.SECONDS);//*连接超时时间*
builder.writeTimeout(1000*60,TimeUnit.SECONDS);//*写操作超时时间*
builder.readTimeout(1000*60,TimeUnit.SECONDS);//*读操作超时时间*
- 加入 retrofit 配置
ApiConfig.BASE_URL = "https://wanandroid.com/";
// 创建 OKHttpClient
OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
httpBuilder.connectTimeout(1000*60, TimeUnit.SECONDS);//连接超时时间
httpBuilder.writeTimeout(1000*60,TimeUnit.SECONDS);//写操作超时时间
httpBuilder.readTimeout(1000*60,TimeUnit.SECONDS);//读操作超时时间
// 创建Retrofit
mRetrofit = new Retrofit.Builder()
.client(httpBuilder.build())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(ApiConfig.BASE_URL)
.build();
- 定义HTTP的API对应的接口:
public interface ApiService {
@GET("wenda/comments/{questionId}/json")
Call<Map<Object,Object>> getWendaList(@Path("questionId") String questionId);
上面的接口定义就会调用服务端URL为wanandroid.com/wenda/comme… 问题id/json需返回定义好对象!
- 请求接口
Call对象有两个请求方法:
1.Enqueue异步请求方法
2.Exectue同步请求方法
异步请求:
public void postAsnHttp(){
ApiService httpList = mRetrofit.create(ApiService.class);
调用实现的方法来进行同步或异步的HTTP请求:
Call<Map<Object, Object>> wendaList = httpList.getWendaList("14500");
wendaList.enqueue(new Callback<Map<Object, Object>>() {
@Override
public void onResponse(Call<Map<Object, Object>> call, Response<Map<Object, Object>> response) {
Log.i("111111","onResponse:"+response.body().toString());
}
@Override
public void onFailure(Call<Map<Object, Object>> call, Throwable t) {
}
});
}
}
同步请求
try {
//同步请求
Response<Map<Object, Object>> response = call1.execute();
If (response.isSuccessful()) {
Log.d("Retrofit2Example", response.body().getDesc());
}
} catch (IOException e) {
e.printStackTrace();
}