Instructions for using Network access

Source: Internet
Author: User

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
    • @Path description
 
   
  1. @GET("group/{id}/users")
  2. 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

    • @Query description
 
   
  1. @GET("users/list")
  2. 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]

  
  1. @GET ( "Group/{id}/users"
  2. 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
 
   
  1. @POST("users/new")
  2. 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
  
  1. @Headers({
  2. "Accept: application/vnd.github.v3.full+json",
  3. "User-Agent: Retrofit-Sample-App"
  4. })
  5. @GET("users/{username}")
  6. 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
 
   
  1. 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
  
  1. public interface RsaHttp {
  2. /**
  3. * 获取rsa公钥
  4. * @return
  5. */
  6. @GET("/rsa")
  7. Observable<BaseResult<Map<String, String>>> getRsaPublicKey();
  8. }

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>> .

    • Network requests
  
  1. observable < Span class= "Typ" >baseresult < map < string string >>> observable = watchhttpcreater create baseurlmanager getdefaulturl (), rsahttp class getrsapublickey
  2. observable.subscribeOn(Schedulers.io())
  3. .observeOn(AndroidSchedulers.mainThread())
  4. .subscribe(new Action1<BaseResult<Map<String, String>>>() {
  5. @Override
  6. public void call ( baseresult < map < string string >> ) {
  7. System.out.println(mapBaseResult.getData().get("publicKey"));
  8. }
  9. });
    • 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.