码迷,mamicode.com
首页 > 移动开发 > 详细

Android探索之基于okHttp打造自己的网络请求<Retrofit+Okhttp>(五)

时间:2016-05-29 13:36:11      阅读:1742      评论:0      收藏:0      [点我收藏+]

标签:

前言:

    通过上面的学习,我们不难发现单纯使用okHttp来作为网络库还是多多少收有那么一点点不太方便,而且还需自己来管理接口,对于接口的使用的是哪种请求方式也不能一目了然,出于这个目的接下来学习一下Retrofit+Okhttp的搭配使用。

Retrofit介绍:

  Retrofit和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

  • Gsoncom.squareup.retrofit2:converter-gson
  • Jacksoncom.squareup.retrofit2:converter-jackson
  • Moshicom.squareup.retrofit2:converter-moshi
  • Protobufcom.squareup.retrofit2:converter-protobuf
  • Wirecom.squareup.retrofit2:converter-wire
  • Simple XMLcom.squareup.retrofit2:converter-simplexml
  • Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

    由于项目中使用的是FastJson,所以只能自己自定义ConverterFactory,不过国内已经有大神对此作了封装(http://www.tuicool.com/articles/j6rmyi7)。

  • FastJson compile ‘org.ligboy.retrofit2:converter-fastjson-android:2.0.2‘

重点看下Factory类的实现

 

abstract class Factory {

    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
        Retrofit retrofit) {
      return null;
    }


    public Converter<?, RequestBody> requestBodyConverter(Type type,
        Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
      return null;
    }


    public Converter<?, String> stringConverter(Type type, Annotation[] annotations,
        Retrofit retrofit) {
      return null;
    }
  }

 

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);

}

  3.get请求 拼接参数 @QueryMap使用

public interface IApi {

 @GET("users/{groupId}")
    Call<List<User>> getUsers(@Path("userId") String userId, @QueryMap HashMap<String, String> paramsMap);

}
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());
        request_tv.setText(response.body());
    }

    @Override
    public void onFailure(Call<String> call, Throwable t) {
        Log.e("", "response----失败");
    }
    });

 

Android探索之基于okHttp打造自己的网络请求<Retrofit+Okhttp>(五)

标签:

原文地址:http://www.cnblogs.com/whoislcj/p/5539239.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!