对Retrofit的认识

对Retrofit的认识android

Retrofit 是基于 OkHttp 封装的一套 RESTful(RESTful是一套api设计的风格) 网络请求框架json

Retrofit是在okhttp基础之上作的封装,项目中能够直接用了。api

Retrofit与Retrofit 2.0(两者分工协做)的区别:markdown

Retrofit是一个RESTful的HTTP网络请求框架的封装,专一于接口的封装。网络

Retrofit 2.0 开始内置 OkHttp,专一于网络请求的高效。框架

经过Retrofit请求网络的原理:使用 Retrofit 接口层封装请求参数、Header、Url 等信息,以后由 OkHttp 完成后续的请求操做,在服务端返回数据以后,OkHttp 将原始的结果交给 Retrofit,后者根据用户的需求对结果进行解析。异步

Retrofit 是一个 RESTful 的 HTTP 网络请求框架的封装,网络请求的工做本质上是 OkHttp 完成,而 Retrofit 仅负责 网络请求接口的封装。ide

Retrofit框架网络请求流程图:post

图片.png

1、与安卓集成gradle

  1. 添加依赖(在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'
复制代码
  1. 加入 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);//*读操做超时时间*
复制代码
  1. 加入 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();
复制代码
  1. 定义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需返回定义好对象!

  1. 请求接口

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();
} 
复制代码
相关文章
相关标签/搜索