Add the dependent
Making search Retrofit
Implementation 'com. Squareup. Retrofit2: retrofit: 2.3.0'Copy the code
Configuration Retrofit
Retrofit = new retrofit. The Builder (). The baseUrl (" http://192.168.18.249:8080/ ") / / this is to test the address. The build ();Copy the code
Defining the Data Interface
Public interface DataServer {// @query ("id"); // @query ("id"); // @query ("id"); // Where id is http://zzz.zzz/user_info? id=userId @GET("user_info") Call<ResponseBody> getUserInfo(@Query("id") Integer userId); }Copy the code
Using the Data Interface
Create a data interface instance, using Retrofit’s Create method
DataServer dataServer = retrofit.create(DataServer.class);
Copy the code
Calling interface methods
Call<ResponseBody>call=dataServer.getUserInfo(5);
Copy the code
Perform request parsing results
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(response.isSuccessful()){
String str = null;
try {
str = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
tv.setText(str);
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
Copy the code
Json parsing:
Dependency conversion module
Implementation 'com. Squareup. Retrofit2: converter - gson: 2.3.0'Copy the code
Add transformation factories that allow you to customize Gson objects
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); / / configuration Retrofit Retrofit = new Retrofit. Builder () baseUrl (" http://192.168.18.249:8080/ ") AddConverterFactory (GsonConverterFactory. Create (gson)) / / add a converter. The build ();Copy the code
For a fixed return json format such as:
{code: 1, data: {}} or {code: 1, data: []}Copy the code
You can encapsulate a basic template
public class BaseData<T>{ private int code; private T data; . }Copy the code
If you want to get a result object, such as a method to get basic user information, you can use the following:
@GET("user_info")
Call<BaseData<User>> getUserInfo(@Query("id") Integer userId);
Call<BaseData<List<Article>>> ...
Copy the code
The analytical results are as follows:
DataServer dataServer=retrofit.create(DataServer.class); Call<BaseData<User>>call=dataServer.getUserInfo(5); call.enqueue(new Callback<BaseData<User>>() { @Override public void onResponse(Call<BaseData<User>> call, Response<BaseData<User>> response) { if(response.isSuccessful()){ BaseData<User> data = response.body(); if(data.getCode()==1) { User u = data.getData(); tv.setText(u.toString()); }else{tv.settext (" fetch failed "); } } } @Override public void onFailure(Call<BaseData<User>> call, Throwable t) { } });Copy the code
OkHttp configuration
Main configuration cache, public parameters, request header information, read and write, connection timeout configuration
private OkHttpClient.Builder getOkHttpBuilder(){ OkHttpClient.Builder builder = new OkHttpClient.Builder(); // Configure the cache size. / MNT/sdcard/Android/data/cache / / application package name weibocache File cacheFile = new File (context) getExternalCacheDir (), "weibocache"); Cache cache = new Cache(cacheFile,1024*1024*50); Interceptor cacheInterceptor = new Interceptor(){@override public Response Intercept (Chain Chain)throws IOException{// Configure the Request mode. Request Request = chain.request(); Request.Builder requestBuilder = request.newBuilder().method(request.method(),request.body()); / / test network connection state if (isConnected ()) {/ / networking state don't read cache requestBuilder cacheControl (cacheControl. FORCE_NETWORK); } else {/ / not connected to the Internet to read cache requestBuilder cacheControl (cacheControl. FORCE_CACHE); } Request newRequest = requestBuilder.build(); Response response = chain.proceed(newRequest); If (isConnected()){ Response = response.newBuilder().removeheader ("Pragma").header(" cache-control ","public,max-age=0") .build(); }else{// Not connected, Response = response.newBuilder().removeheader ("Pragma") .header("Cache-Control","public,only-if-cached,max-stale="+(60*60*24*7)) .build(); } return response; }}; Cache.cache (cache).addInterceptor(cacheInterceptor); ReadTimeout (30, timeunit.seconds); builder.writeTimeout(30,TimeUnit.SECONDS); builder.connectTimeout(30,TimeUnit.SECONDS); / / error reconnection builder. RetryOnConnectionFailure (true); return builder; }Copy the code
Add the configuration
Retrofit = new retrofit. The Builder (). The baseUrl (" http://192.168.18.249:8080/ "); / / add a converter. AddConverterFactory (GsonConverterFactory. Create (gson)). The client (getOkHttpBuilder (). The builder ()) / / okHttp configuration .build();Copy the code
annotations
Basic request methods @get, @post, @put, @head, @delete, and so onCopy the code
Annotations used in the URL address
@query adds a single parameter (String and basic data type) @queryMap Adds multiple parameters of type Map<String,String>Copy the code
The form
@Formurlencoded a form content submission (submit a string) @multipart a form with files (upload a file) @field a string parameter @fieldMap multiple string parameters @Part a single file, Part@partmap Upload multiple files. The data type is Map<String, multipart. Part>.Copy the code
Share with you
I want to work my way up
Fly forward on the blades at the highest point
Let the wind blow dry tears and sweat
I want to work my way up
Waiting for the sun to watch its face
Little days have big dreams
I have my day
Let the wind blow dry tears and sweat
One day I will have my day