Retrofit2.0 profile

Retrofit is a RESTful Android(Java) client implementation based on annotations that provides JSON to POJO(Plain Ordinary Java Object), POJO to JSON, web requests (POST, GET,PUT, DELETE, etc.) encapsulation. With their own official introduction is:

A type-safe REST client for Android and Java

Has been updated to the 2.0 version, and 1.0 version of the use of the difference is not small, I am the first time to use, here is the main and we study the 2.0 version of simple use. Also refer to the official example.

The preparatory work

Add permissions

First add network request permissions

<uses-permission android:name="android.permission.INTERNET"/>Copy the code

Add the dependent

Retrofit2.0 only supports okhttp requests, which are already packaged, so you don’t need to add okhttp dependencies.

Dependencies {the compile 'com. Squareup. Retrofit2: retrofit: 2.0.2' compile 'com. Squareup. Retrofit2: converter - gson: 2.0.0 -beta3'}Copy the code

Simple to use

Next, take a look at Retrofit initialization and how to request data.

Initialize the Retrofit object

public static final String BASE_URL = "https://api.github.com/";
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build();Copy the code

BASE_URL is the Server address you requested.

.addConverterFactory(GsonConverterFactory.create())Copy the code

Retrofit2.0 does not provide a default parsing method for returning JSON data. You need to specify this method manually and support multiple parsing methods such as Jackson. Add the corresponding dependencies as needed, in this case the Converter-Gson dependencies provided by Retrofit. Unfortunately, FastJson parsing is not supported. If necessary, you can write a FastjsonConverterFactory extension to Converter. Although Retrofit2.0 only supports OKHTTP requests, you can also customize an OKHTTP and configure it into Retrofit.

OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());
            // Do anything with response here
            return response;
        }
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(client)
        .addConverterFactory(GsonConverterFactory.create())
        .build();
});Copy the code

Define the request interface

To convert HTTP apis to Java interfaces, Retrofit provides five built-in annotations: GET, POST, PUT, DELETE, and HEAD, relative urls of the resources specified in the annotations.

public interface NetWorkService {
    @GET("users/basil2style")
    Call<DataBean> getData(a);
}Copy the code

Dynamic updates are made with replacement blocks, which are alphanumeric strings surrounded by {and}, and parameters that must be annotated with @path using the same string.

@GET("repos/{params1}/{params2}/contributors")
Call<List<DataBean2>> getData(
        @Path("params1") String params1,
        @Path("params2") String params2,
);Copy the code

Retrofit creates this URL when we call the getData() method. If we pass the Square and Retrofit strings as the owner and REPO parameters, respectively. We will get the URL:api.github.com/repos/squar… Adding query Parameters

@GET("repos/square/{retrofit}/contributors")
Call<List<DataBean2>> groupData(@Path("retrofit") String retrofit, @Query("sort") String sort);Copy the code

When we call the getData () method, is introduced into a query string parameters “ok”, so that we can get URL:api.github.com/repos/squar… Of course, if the query parameters are too many, we can also use Map to combine and then pass in.

@GET("repos/square/{retrofit}/contributors")
Call<List<DataBean2>> getData(@Path("repos") String repos, @QueryMap Map<String, String> parameters);Copy the code

The request data

Retrifot supports both synchronous and asynchronous requests and uses Retrofit to generate an implementation of the interface NetWorkService.

NetWorkService service = retrofit.create(NetWorkService.class);Copy the code
A synchronous request
Call<DataBean> call = service.getData(Square,Retrofit);
DataBean bean = call.execute().body();Copy the code

Note that synchronous requests cannot be executed on the main thread, as you know. Call can execute the execute() method only once. To request it again, call

call = call.clone() can be used to copy another call object.

An asynchronous request
call.enqueue(new Callback<DataBean>() {
    @Override
    public void onResponse(Call<DataBean> call, Response<DataBean> response) {
        Toast.makeText(MainActivity.this."Request successful", Toast.LENGTH_SHORT).show();
        DataBean bean = response.body();
        tvMain.setText(bean.toString());
    }
    @Override
    public void onFailure(Call<DataBean> call, Throwable t) {}});Copy the code

We can always use the call.cancel() method to cancel the request when the synchronous or asynchronous one we performed is enqueued.

Pay attention to

Note how to concatenate the parameters in the annotation with the BASE_URL.

Error Example 1

BASE_URL:api.github.com/repos/squar… Get comments: @ Get URL:api.github.com/basil2style (“/basil2style “) results

Error Example 2

BASE_URL:api.github.com/repos/squar… Get comments: @ the Get (” basil2style “) results URL:api.github.com/repos/basil…

Recommend writing

BASE_URL:api.github.com/repos/squar… Get comments: @ the Get (” basil2style “) results URL:api.github.com/repos/squar…

conclusion

With the basic implementation of Retrofit2.0 out of the way, Retrofit+Okhttp+Gson is a pretty fast super network request framework for now. Even faster than Volley, the test results were great. Friends hurry up! If you have any questions or questions, you can also put forward them in the Issues of my Github Retrofit2Demo project. I will answer them in time. Attach the address of Retrofit2Demo: Retrofit2Demo