Android中Retrofit+OkHttp进行HTTP网络编程的使用指南

Retrofit介绍:Retrofit(GitHub主页https://github.com/square/okhttp)和OkHttp师出同门,也是Square的开源库,它是一个类型安全的网络请求库,Retrofit简化了网络请求流程,基于OkHtttp做了封装,解耦的更彻底:比方说通过注解来配置请求参数,通过工厂来生成CallAdapter,Converter,你可以使用不同的请求适配器(CallAdapter), 比方说RxJava,Java8, Guava。你可以使用不同的反序列化工具(Converter),比方说json, protobuff, xml, moshi等等。官网 http://square.github.io/retrofit/github https://github.com/square/retrofit

Retrofit使用:1.在build.gradle中添加如下配置

compile 'com.squareup.retrofit2:retrofit:2.0.2'

2.初始化Retrofit

   retrofit = new Retrofit.Builder()        .baseUrl(BASE_URL)        .addConverterFactory(FastJsonConverterFactory.create())        .client(mOkHttpClient)        .build();

3.初始化OkHttpClient

    OkHttpClient.Builder builder = new OkHttpClient().newBuilder()        .connectTimeout(10, TimeUnit.SECONDS)//设置超时时间        .readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间        .writeTimeout(10, TimeUnit.SECONDS);//设置写入超时时间    int cacheSize = 10 * 1024 * 1024; // 10 MiB    Cache cache = new Cache(App.getContext().getCacheDir(), cacheSize);    builder.cache(cache);    builder.addInterceptor(interceptor);    mOkHttpClient = builder.build();

关于okHttp的拦截器、Cache-Control等这里就不再做解说了

4.关于ConverterFactory对于okHttpClient的初始化我们都已经很熟悉了,对ConverterFactory初次接触多少有点陌生,其实这个就是用来统一解析ResponseBody返回数据的。

常见的ConverterFactory

Gson: com.squareup.retrofit2:converter-gsonJackson: com.squareup.retrofit2:converter-jacksonMoshi: com.squareup.retrofit2:converter-moshiProtobuf: com.squareup.retrofit2:converter-protobufWire: com.squareup.retrofit2:converter-wireSimple XML: com.squareup.retrofit2:converter-simplexmlScalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

由于项目中使用的是FastJson,所以只能自己自定义ConverterFactory。

5.定义接口 get 请求(1)get请求 不带任何参数

public interface IApi {  @GET("users")//不带参数get请求  Call<List<User>> getUsers();}

(2)get请求 动态路径 @Path使用

public interface IApi {  @GET("users/{groupId}")//动态路径get请求  Call<List<User>> getUsers(@Path("userId") String userId);}

(3)get请求 拼接参数 @Query使用

public interface IApi {  @GET("users/{groupId}")  Call<List<User>> getUsers(@Path("userId") String userId, @Query("age")int age);}

6.定义接口 post请求(1)post请求 @body使用

public interface IApi {  @POST("add")//直接把对象通过ConverterFactory转化成对应的参数  Call<List<User>> addUser(@Body User user);}

(2)post请求 @FormUrlEncoded,@Field使用

public interface IApi { @POST("login")  @FormUrlEncoded//读参数进行urlEncoded  Call<User> login(@Field("userId") String username, @Field("password") String password);}

(3)post请求 @FormUrlEncoded,@FieldMap使用

public interface IApi {  @POST("login")  @FormUrlEncoded//读参数进行urlEncoded  Call<User> login(@FieldMap HashMap<String, String> paramsMap);}

(4)post请求 @Multipart,@Part使用

public interface IApi {  @Multipart  @POST("login")  Call<User> login(@Part("userId") String userId, @Part("password") String password);}

7.Cache-Control缓存控制

public interface IApi {  @Headers("Cache-Control: max-age=640000")  @GET("users")//不带参数get请求  Call<List<User>> getUsers();}

8.请求使用(1)返回IApi

  /**   * 初始化Api   */  private void initIApi() {    iApi = retrofit.create(IApi.class);  }  /**   * 返回Api   */  public static IApi api() {    return api.iApi;  }

(2)发送请求

  Call<String> call = Api.api().login(userId,password);  call.enqueue(new Callback<String>() {  @Override  public void onResponse(Call<String> call, Response<String> response) {    Log.e("", "response---->" + response.body());  }  @Override  public void onFailure(Call<String> call, Throwable t) {    Log.e("", "response----失败");  }  });

9.拦截器配置

拦截器配置要点引入依赖:

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'compile 'com.squareup.okhttp3:okhttp:3.0.1'compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'

先说 OkHttp 3.0 的配置,3.0 使用层面上的主要改变是,由原本的 okHttp 对象直接各种 set 进行配置改为 Builder 配置模式,所以原本对应的方法应该到 OkHttpClient.Builder 类对象下寻找。我的一些常用配置如下:

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);OkHttpClient client = new OkHttpClient.Builder()    .addInterceptor(interceptor)    .retryOnConnectionFailure(true)    .connectTimeout(15, TimeUnit.SECONDS)    .addNetworkInterceptor(mTokenInterceptor)    .build();

解释:(1)HttpLoggingInterceptor 是一个拦截器,用于输出网络请求和结果的 Log,可以配置 level 为 BASIC / HEADERS / BODY,都很好理解,对应的是原来 retrofit 的 set log level 方法,现在 retrofit 已经没有这个方法了,所以只能到 OkHttp 这边来配置,并且 BODY 对应原来到 FULL.(2)retryOnConnectionFailure 方法为设置出现错误进行重新连接。(3)connectTimeout 设置超时时间(4)addNetworkInterceptor 让所有网络请求都附上你的拦截器,我这里设置了一个 token 拦截器,就是在所有网络请求的 header 加上 token 参数,下面会稍微讲一下这个内容。让所有网络请求都附上你的拦截器:

Interceptor mTokenInterceptor = new Interceptor() {  @Override public Response intercept(Chain chain) throws IOException {    Request originalRequest = chain.request();    if (Your.sToken == null || alreadyHasAuthorizationHeader(originalRequest)) {      return chain.proceed(originalRequest);    }    Request authorised = originalRequest.newBuilder()      .header("Authorization", Your.sToken)      .build();    return chain.proceed(authorised);  }};

解释:(1)那个 if 判断意思是,如果你的 token 是空的,就是还没有请求到 token,比如对于登陆请求,是没有 token 的,只有等到登陆之后才有 token,这时候就不进行附着上 token。另外,如果你的请求中已经带有验证 header 了,比如你手动设置了一个另外的 token,那么也不需要再附着这一个 token.(2)header 的 key 通常是 Authorization,如果你的不是这个,可以修改。(3)如果你需要在遇到诸如 401 Not Authorised 的时候进行刷新 token,可以使用 Authenticator,这是一个专门设计用于当验证出现错误的时候,进行询问获取处理的拦截器:

Authenticator mAuthenticator = new Authenticator() {  @Override public Request authenticate(Route route, Response response)      throws IOException {    Your.sToken = service.refreshToken();    return response.request().newBuilder()            .addHeader("Authorization", newAccessToken)            .build();      }}

然后,对于以上的两个拦截器,分别使用 OkHttpClient.Builder 对象的 addNetworkInterceptor(mTokenInterceptor) 和 authenticator(mAuthenticator) 即可。Retrofit:对于 Retrofit,我的配置是:

Retrofit retrofit = new Retrofit.Builder()    .baseUrl(AppConfig.BASE_URL)    .client(client)    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())    .addConverterFactory(GsonConverterFactory.create(gson))    .build();service = retrofit.create(YourApi.class);

解释:(1)baseUrl: 原来的 setEndPoint 方法变成了 baseUrl(2)client 即上面的 OkHttp3 对象(3)addCallAdapterFactory 增加 RxJava 适配器(4)addConverterFactory 增加 Gson 转换器

如果困难是地上的荆棘,我们脱掉鞋子,光着脚笑笑,

Android中Retrofit+OkHttp进行HTTP网络编程的使用指南

相关文章:

你感兴趣的文章:

标签云: