I. Highlights:
Since the release of Hongmeng mobile version, I have been working on porting android code to hongmeng system. Retrofit is an excellent network request framework for Android. Hongmeng doesn’t have a similar network request framework. So I decided to implement Retrofit in a big way.
JianJia is a network request framework on The Hongmeng system, which is basically a port of Android Retrofit to The Hongmeng system, which I named JianJia. The project would not only implement Retrofit’s functions, but would also provide some functions that Retrofit didn’t. Retrofit does not support dynamic domain name replacement. Domestic applications generally have multiple domain names, so dynamic domain name replacement is supported. Retrofit was not able to add interceptors directly, only through OKHTTP, which the Team supported.
Ii. Demo compilation and effect presentation are as follows:
Demo Demo video stamp this
Note: The document attachment is at the bottom
Three, source code:
Gitee.com/zhongte/Jia…
To read the source code, you need to have the following skills.
Familiarize yourself with the common uses of OKHTTP
Familiar with interface oriented programming, reflection, generics, annotations
Familiar with the constructor pattern, adapter pattern, factory pattern, policy pattern, static proxy, dynamic proxy, responsibility chain pattern and other design patterns
The usage is the same as Retrofit
The Time provides a series of annotations that are required when making web requests.
4.1 GET annotations
Create an interface, put a GET annotation inside the method, and the GET annotation identifies that this is a GET request, the return value of the method is a Call object, and the generic is ResponseBody, but the generic can also be a concrete entity object, more on that later. How does the Network request be completed? BaseUrl is the domain name. The domain name must be specified when jianjia is created. The create method is called to generate an instance of the interface, wan.getbanner ().enqueue is called to execute the network request, onResponse is called on success and onFailure is called onFailure
public interface Wan {
@GET("banner/json")
Call<ResponseBody> getBanner(a);
}
JianJia jianJia = new JianJia.Builder()
.baseUrl("https://www.wanandroid.com")
.build();
Wan wan = jianJia.create(Wan.class);
wan.getBanner().enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String json = response.body().string();
} catch(IOException e) { e.printStackTrace(); }}@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
LogUtils.info("yunfei", t.getMessage()); }});Copy the code
4.2 BaseUrl annotations
Domestic applications generally have multiple domain names. BaseUrl annotations can set a separate domain name for an interface.
public interface Wan {
@BaseUrl("https://api.apiopen.top")
@GET("getJoke")
Call<ResponseBody> getJoke(@QueryMap Map<String, String> param);
}
Copy the code
4.3 the Path annotations
The Path annotation replaces the specified parameter values in the Path, defining the following methods. As you can see, we define a getArticle method that takes a page argument, and our @get annotation declares the access Path with {page}, where you can use {page} as a placeholder, which will be replaced by @path (“page”) as an argument.
public interface Wan {
@GET("article/list/{page}/json")
Call<ResponseBody> getArticle(@Path("page") int page);
}
Copy the code
4.4 the Query annotation
Query annotations are used to add request parameters to GET requests. The parameter types modified by Query annotations can be arrays, collections, strings, and so on
public interface Wan {
@GET("wxarticle/list/405/1/json")
Call<ResponseBody> search(@Query("k") String k);
@GET("wxarticle/list/405/1/json")
Call<ResponseBody> search(@Query("k") String... k);
@GET("wxarticle/list/405/1/json")
Call<ResponseBody> search(@Query("k") List<String> k);
}
Copy the code
4.5 QueryMap annotations
QueryMap annotations add query parameters in the form of a map. The parameter types modified by QueryMap annotations must be Map objects
public interface Wan {
@GET("wxarticle/list/405/1/json")
Call<ResponseBody> search(@QueryMap Map<String, String> param);
}
Copy the code
4.6 SkipCallbackExecutor annotations
On a cloud system, the server’s response is called back to the main thread by default. If SkipCallbackExecutor annotations are used on methods, the server’s result is not called back to the main thread
public interface Wan {
@SkipCallbackExecutor
@GET("wxarticle/list/405/1/json")
Call<ResponseBody> search(@QueryMap Map<String, String> param);
}
Copy the code
4.7 FormUrlEncoded annotations and Field annotations
FormUrlEncoded annotations are used to send a form request, and Field annotations must be added to the parameters of a method. The parameter types modified by Field annotations can be arrays, collections, strings, and so on
public interface Wan {
@POST("user/login")
@FormUrlEncoded
Call<ResponseBody> login(@Field("username") String username, @Field("password") String password);
}
Copy the code
4.8 FormUrlEncoded annotations and FieldMap annotations
Sometimes the form will have too many parameters, and if you use the Field annotation, the method will have too many parameters. In this case, you can use the FieldMap annotation, which sends a form request as a map. If the parameter modified by the FieldMap annotation is not of Map type, an exception is thrown. If the Map’s key-value pair is empty, an exception is thrown.
public interface Wan {
@POST("user/login")
@FormUrlEncoded
Call<ResponseBody> login(@FieldMap Map<String, String> map);
}
Copy the code
4.9 the Body annotations
The server will ask the server to send the JSON string as the request body. At this point, the parameters defined using the Body annotation can be passed directly to an entity class, which will be serialized internally and the serialized result sent directly as the request Body.
If the type of the parameter modified by the Body annotation is a RequestBody object, the caller can omit the data converter and use the default data converter internally
If the type of the parameter modified by the Body annotation is not a RequestBody object but a concrete entity class, then the caller needs to customize a class and inherit Converter
public interface Wan {
/** * The type of the argument to be modified by the Body annotation is the RequestBody object, so the caller can use the default data converter internally instead of adding it@param body
* @return* /
@POST("user/register")
Call<ResponseBody> register(@Body RequestBody body);
/** * The type of the parameter to be modified by the Body annotation is not a RequestBody object. It is a concrete entity class, and the caller needs to define a class that inherits Converter@param user
* @return* /
@POST("user/register")
Call<ResponseBody> register(@Body User user);
}
Copy the code
4.10 the Url annotations
The Url annotation is used to add the full address of the interface. In Retrofit, if the domain name of the interface is not the same as the domain name specified to create the Retrofit object, Url annotations are used to resolve the problem. Url annotations can also be used to solve the problem in the Case, but the Case also provides BaseUrl to solve the problem.
public interface Wan {
@GET()
Call<ResponseBody> getArticle(@Url String url);
}
Copy the code
4.11 Headers annotations
The Headers annotation is an annotation applied to a method to add one or more request Headers.
public interface Wan {
@Headers("Cache-Control: max-age=640000")
@GET("/")
Call<ResponseBody> getArticle(@Url String url);
@Headers({ "X-Foo: Bar", "X-Ping: Pong" })
@GET("/")
Call<ResponseBody> getArticle(@Url String url);
}
Copy the code
4.12 the Header comment
Header annotations are annotations applied to parameters to add request headers
public interface Wan {
@GET()
Call<ResponseBody> foo(@Header("Accept-Language") String lang);
}
Copy the code
4.13 HeaderMap annotations
A HeaderMap annotation is an annotation that applies to parameters and adds headers in the form of a map. The key and value of each item in the map cannot be empty, otherwise an exception will be thrown
public interface Wan {
@GET("/search")
Call<ResponseBody> list(@HeaderMap Map<String, String> headers);
}
Copy the code
Add a data converter
When we defined a method in the interface earlier, the return value of the method was a Call object and the generic type was ResponseBody. In this case, the data that the server returns to the ResponseBody is in the ResponseBody, and the responseneeds to manually parse the JSON into an entity class.
In fact, we don’t need to parse json manually, we can have Gson parse json for us. The case supports the addition of data converters, which are added at object creation time, that is, adding Gson. In the onResponse method, you can get the entity class object directly. Gson helps us parse json into an entity class.
public interface Wan {
@GET("banner/json")
Call<Banner> getBanner(a);
}
JianJia jianJia = new JianJia.Builder()
.baseUrl("https://www.wanandroid.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
Wan wan = jianJia.create(Wan.class);
wan.getBanner().enqueue(new Callback<Banner>() {
@Override
public void onResponse(Call<Banner> call, Response<Banner> response) {
try {
if(response.isSuccessful()) { Banner banner = response.body(); }}catch(IOException e) { e.printStackTrace(); }}@Override
public void onFailure(Call<Banner> call, Throwable t) {
LogUtils.info("yunfei", t.getMessage()); }});Copy the code
Six, the follow-up work
6, 1 upload files also need to use annotations. At present, there is no annotation for uploading files, and the annotation for uploading files is under development. 6, 2 Currently, the project does not support the direct addition of interceptors, and the functions of interceptors will be added later. 6. 3 Secondary encapsulation of network request framework. The secondary encapsulation of network request framework should isolate the third-party network framework. 6, 4 due to the epidemic, I guess I have to spend the Spring Festival in Beijing, and can’t go back to my hometown. So I can make a video for you during the break. Hand in hand to achieve their own network framework, I hope to help you understand the realization of the principle. Of course, the principle behind the Implementation of the Project was exactly the same as Retrofit. The case itself is a transplant from Retrofit, but it can be run on the Hongmeng system.
The original link: developer.huawei.com/consumer/cn…
Original author: Yi Bo Yuntian Xiao Guan Yu