Retrofit概念
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<CommentResponse> getWendaList(@Path("questionId") String questionId);
}
上面的接口定义就会调用服务端URL为wanandroid.com/wenda/comme… 需返回定义好对象
返回对象定义
public class CommentResponse {
private Integer errorCode;
private String errorMsg;
private CommentBean date;
}
public class CommentBean {
private int total;
private int size;
private List<CommentData> datas;
class CommentData{
private int articleId;
private boolean canEdit;
private String content;
private int id;
private String niceDate;
private Date publishDate;
private int rootCommentId;
private int status;
private int toUserId;
private String toUserName;
private int userId;
private String userName;
private int zan;
}
}
5. 请求接口
Call对象有两个请求方法: 1.Enqueue异步请求方法; 2.Exectue同步请求方法
异步请求:
public void postAsnHttp(){
ApiService httpList = mRetrofit.create(ApiService.class);
调用实现的方法来进行同步或异步的HTTP请求:
Call<CommentResponse> wendaList = httpList.getWendaList("14500");
wendaList.enqueue(new Callback<CommentResponse>() {
@Override
public void onResponse(Call<Map<Object, Object>> call, Response<CommentResponse> response) {
Log.i("111111","onResponse:"+response.body().toString());
}
@Override
public void onFailure(Call<Map<Object, Object>> call, Throwable t) {
}
});
}
}
同步请求
try {
//同步请求
Response<CommentResponse> response = call1.execute();
If (response.isSuccessful()) {
Log.d("Retrofit2Example", response.body().getDesc());
}
} catch (IOException e) {
e.printStackTrace();
}