Retrofit 是一个 RESTful 的 HTTP 网络请求框架的封装,网络请求的工作本质上是 OkHttp 完成,而 Retrofit 仅负责 网络请求接口的封装。
Retrofit框架网络请求流程图:
一、与安卓集成
1. 添加依赖
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'
复制代码
2. 加入 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);//读操作超时时间
复制代码
3. 加入 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();
复制代码
4. 定义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需返回定义好对象!
5. 请求接口
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();
}
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END