Instructions for using Network access
Network access is encapsulated based on rxjava+retrofit2+okhttp, so users are required to familiarize themselves with the Rxjava basic functionality, related learning documents: http://blog.csdn.net/meegomeego/article/details/49155989/.
1. retrofit2 annotations Using simple instructions
Retrofit2 HTTP request convenience annotations include: Get, post, put, delete, HEAD, corresponding to the RESTful server interface related request method, generally we will only use the GET, post, put, DELETE these four methods. In addition, the Header,url,body for the HTTP protocol also has a corresponding note, the official documentation: http://square.github.io/retrofit/.
1.1.url related annotations
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);
We want to in the URL, the dynamic transfer request parameter, can be written in {param} format, and use @path ("param") on the function corresponding parameter variable annotation can be, such as the above example groupid the value of 10, then the actual request URL address is: group/ 10/users
@GET("users/list")
Call<List<User>> groupList(@Query("sort") String sort);
There is also a more common way to add after the request address, and then in the form of key=value, for example, we want to send the server a variable named sort, the variable value is desc parameter, We can write annotations in the way above. The URL for the actual request is: Users/list?sort=desc.
[Email protected]
@GET ( "Group/{id}/users"
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
@Query way, can only satisfy us to transmit a parameter, when we want to use this format to transfer a set of parameters, we can use the @QueryMap.
1.2.body related annotations
@POST("users/new")
Call<User> createUser(@Body User user);
By adding a @body annotation to a method parameter, you can indicate that the object is the body parameter of the request, and Retrofit2 will serialize according to the converterfactory you configured, such as configuring Jacksonconverterfactory, Then the request body is serialized into JSON format.
In addition, the RETROFIT2 also supports form submission, and so on, the server unified use JSON for data communication, this is not discussed here.
1.3.header related annotations
@Headers({
"Accept: application/vnd.github.v3.full+json",
"User-Agent: Retrofit-Sample-App"
})
@GET("users/{username}")
Call<User> getUser(@Path("username") String username);
@Headers can add a fixed header request information to the HTTP request, if you want to add header fixed information to each request, it is best to do the unified processing in the Okhttp interceptor, avoid adding this kind of information to each network interface, appear redundant.
2. Business Server access
This functionality is encapsulated because the business Server needs to transmit a fixed request header, as well as a signature requirement.
2.1. Initialization
WatchHttpCreater.init(new WatchDevice(context), new LauncherAppInfo(context), null);
The function needs to be called in application's OnCreate method, only one initialization is required, and repeated initialization throws RuntimeException, where the purpose of initialization is primarily in interceptors, for server-specific signatures and parameter requirements, This type of data needs to be processed.
2.2. Network Request Example
- HTTP Interface Declaration
public interface RsaHttp {
/**
* 获取rsa公钥
* @return
*/
@GET("/rsa")
Observable<BaseResult<Map<String, String>>> getRsaPublicKey();
}
Baseresult The class is a fixed object returned by the server, because there are different types of data objects in Baseresult, in order to facilitate JSON parsing at the bottom level, it is necessary to declare the type of data, such as the data returned by the interface as a Map<String, String> type. So the return data is declared as BaseResult<Map<String, String>> .
observable < Span class= "Typ" >baseresult < map < string string >>> observable = watchhttpcreater create baseurlmanager getdefaulturl (), rsahttp class getrsapublickey
observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<BaseResult<Map<String, String>>>() {
@Override
public void call ( baseresult < map < string string >> ) {
System.out.println(mapBaseResult.getData().get("publicKey"));
}
});
- Subscribeon
An event occurs on the thread that the network request declares that the event occurs on the IO thread.
- Observeon
Event consuming thread, if not stated, event consuming thread will and occurs thread on the same thread, if it involves UI action, declare it as the main thread of Android, otherwise you do not have to declare it.
- Baseurlmanager
The same class manages the domain name information related to Business Server network requests, facilitates global switching of domain names, and tests are often performed in multiple server environments.
3. More information
When used, then perfect ...
From for notes (Wiz)
Instructions for using Network access