Preface:

From the above learning, it is not difficult to find that simply using okHttp as a network library is a little bit inconvenient, and you also need to manage the interface by yourself, and it is not clear at a glance what kind of request method is used for the interface. For this purpose, we will learn Retrofit+ okHttp.

Retrofit is introduced:

Square’s open source library, Retrofit, is a type-safe web request library. Retrofit simplifies the web request process, encapsulating it based on OkHtttp, and decoupling it more thoroughly: for example, configuring request parameters through annotations, To generate callAdapters from factories, you can use different request adapters, such as RxJava, Java8, Guava. You can use different deserialization tools (Converter) such as JSON, Protobuff, XML, Moshi, etc.

  • The website http://square.github.io/retrofit/
  • github https://github.com/square/retrofit

Retrofit using:

1.) Add the following configuration to build.gradle
The compile 'com. Squareup. Retrofit2: retrofit: 2.0.2'Copy the code

2.) Initialize Retrofit
     retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(FastJsonConverterFactory.create())
                .client(mOkHttpClient)
                .build();Copy the code

3.) Initialize OkHttpClient
OkHttpClient.Builder builder = new OkHttpClient().newBuilder() .connectTimeout(10, Timeununit.seconds)// set timeout. ReadTimeout (10, timeunit.seconds)// set readTimeout. 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();Copy the code

OkHttp interceptors, cache-control, etc. are not explained here

4.) About ConverterFactory

We’re all familiar with the initialization of okHttpClient, somewhat unfamiliar to the ConverterFactory for the first time, and this is actually used to parse the ResponseBody return data uniformly.

Common ConverterFactory

  • Gson: com.squareup.retrofit2:converter-gson
  • Jackson: com.squareup.retrofit2:converter-jackson
  • Moshi: com.squareup.retrofit2:converter-moshi
  • Protobuf: com.squareup.retrofit2:converter-protobuf
  • Wire: com.squareup.retrofit2:converter-wire
  • Simple XML: com.squareup.retrofit2:converter-simplexml
  • Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

Because FastJson is used in the project, so only their own custom ConverterFactory, but domestic have great god has made the package (http://www.tuicool.com/articles/j6rmyi7).

  • FastJson compile ‘org. Ligboy. Retrofit2: converter – FastJson – android: 2.0.2’
5.) Define interface GET requests

1. The GET request does not contain any parameters

Public interface IApi {@get ("users")// GET request Call> getUsers(); }Copy the code

2. Get requests dynamic path@path

Public interface IApi {@get ("users/{groupId}")// dynamic Path GET request Call> getUsers(@path ("userId") String userId); }Copy the code

3. The @query parameter is used by get

public interface IApi {

    @GET("users/{groupId}")
    Call> getUsers(@Path("userId") String userId, @Query("age")int age);

}Copy the code

3. The get request concatenation parameter @queryMap is used

public interface IApi {

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

}Copy the code

6.) Define interface POST requests

1. Post requests @body to use

Public interface IApi {@post ("add")// Convert the object directly to the corresponding argument Call> addUser(@body User User); }Copy the code

2. Post request @formurlencoded, @field used

Public interface IApi {@post ("login") @urlencoded // Read parameters urlEncoded Call login(@field ("userId") String username, @Field("password") String password); }Copy the code

3. Post request @formurlencoded, @fieldMap used

Public interface IApi {@post ("login") @formurlencoded // Read parameters urlEncoded Call login(@fieldMap HashMap paramsMap); }Copy the code

4. Post requests @multipart, which is used by @part

public interface IApi {

    @Multipart
    @POST("login")
    Call login(@Part("userId") String userId, @Part("password") String password);

}Copy the code

7.) cache-control
Public interface IApi {@headers (" cache-control: max-age=640000") @get ("users"); public interface IApi {@headers (" cache-control: max-age=640000") @get ("users") }Copy the code

8.) Request use

1. Return IApi

/** * Private void initIApi() {iApi = retrofit.create(iapi.class); } /** * return Api */ public static Api () {return Api. }Copy the code

2. Send the request

Call call = Api.api().login(userId,password); call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { Log.e("", "response---->" + response.body()); } @override public void onFailure(Call Call, Throwable t) {log.e ("", "response---- failed "); }});Copy the code