Retrofit is a RESTful encapsulation of the HTTP web request framework. The work of the web request is essentially done by OkHttp, and Retrofit is only responsible for the encapsulation of the web request interface.

Retrofit Framework Network request flowchart:

1. Integration with Android

1. Add a dependency

Build. Gradle: The first is to add retrofit, the second and third are to add JSON parsing, in this case is 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'Copy the code

2. Add the OkHttp configuration

// Create OKHttpClient okHttpClient.builder Builder = new okHttpClient.builder (); builder.connectTimeout(1000*60, TimeUnit.SECONDS); Builder.writetimeout (1000*60, timeunit.seconds); Build.readtimeout (1000*60, timeunit.seconds); // Read timeoutCopy the code

3. Add the Retrofit configuration

ApiConfig.BASE_URL = "https://wanandroid.com/"; // Create 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); // Create Retrofit mRetrofit = new Retrofit.builder ().client(httpBuilder.build()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(ApiConfig.BASE_URL) .build();Copy the code

4. Define the HTTP API corresponding to the interface:

 public interface ApiService {
 
   @GET("wenda/comments/{questionId}/json") 
   Call<Map<Object,Object>> getWendaList(@Path("questionId") String questionId); 


Copy the code

The interface definition above is called the server URL for wanandroid.com/wenda/comme… Problem ID /json needs to return a defined object!

5. Request interface

The Call object has two request methods: 1. The Enqueue asynchronous request method; 2.Exectue Synchronous request method

Asynchronous request: public void postAsnHttp(){ApiService httpList = mretrofit.create (ApiService. Class); Call the implementation method to make synchronous or asynchronous HTTP requests: 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) { } }); }} Sync request try {// Sync request Response<Map<Object, Object>> Response = call1.execute(); If (response.isSuccessful()) { Log.d("Retrofit2Example", response.body().getDesc()); } } catch (IOException e) { e.printStackTrace(); }Copy the code