Retrofit is a network request library based on OkHttp encapsulation, a type-safe HTTP client for Android and Java. Retrofit requires at least Java 8+ or Android API 21+. The github website of Retrofit is https://github.com/square/retrofit.
Retrofit basic settings
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://gank.io/api/v2/data/category/Girl/type/Girl/")// Set BaseURL to end with'/'
.addConverterFactory(GsonConverterFactory.create())// json parser Gson
.callbackExecutor(Executors.newSingleThreadExecutor())// Use a separate thread
.build();// Create Retrofit object
Create request API
public interface Api {
@GET("page/1/count/10/")
Call<Response<DemoBean>> getCall();
Data entity class
public class DemoBean {
private List<Data> data;
private int page;
private int page_count;
private int status;
private int total_counts;
public void setData(List<Data> data) {
this.data = data;
}
public List<Data> getData() {
return data;
}
public void setPage(int page) {
this.page = page;
}
public int getPage() {
return page;
}
public void setPage_count(int page_count) {
this.page_count = page_count;
}
public int getPage_count() {
return page_count;
}
public void setStatus(int status) {
this.status = status;
}
public int getStatus() {
return status;
}
public void setTotal_counts(int total_counts) {
this.total_counts = total_counts;
}
public int getTotal_counts() {
return total_counts;
}
}
The entity class can delete unnecessary fields according to the situation.
Call interface method
public void request(){
Api api = retrofit.create(Api.class);// Create Api proxy object
Call<DemoBean> call = api.getCall();// Call interface method
call.enqueue(new Callback<DemoBean>() {
@Override
public void onResponse(Call<DemoBean> call, Response<DemoBean> response) {
// Request success callback
Log.d("Retrofit", "onResponse: "+response.body().toString());
}
@Override
public void onFailure(Call<DemoBean> call, Throwable t) {
// Request failed callback
}
});
Interface methods cannot be called directly, you need to use Retrofit to create Api proxy objects.
To sum up
This article briefly describes the use of Retrofit. The general process used by Retrofit is: create a Retrofit instance and make some basic settings, then create a request interface, set the request method and declare the return data type, and finally use Retrofit to create an interface object and implement the interface Method to send network request.