Initial use of fit2.0 and fit2.0

Source: Internet
Author: User

Initial use of fit2.0 and fit2.0

Initial use of Retrofit2.0

First of all I will not introduce, directly talk about how to use, itself is just because of the Microsoft azure-sdk-for-java (git address is: https://github.com/Azure/azure-sdk-for-java.git)
Then, compile a similar program and design the program into "fit.
I used it just now, so I'm sure I don't know how it works. So I am here to tell you how to use it. Some of the Code in it is not very good. I hope you can point it out together, I will correct it slowly. Please forgive me.

First, I encapsulated Retrofit and OkHttpClient in RestCline. Of course, we can also use Retrofit separately. The usage is the same. Because the Gosn converter is added, we need to add a Gson dependency package, I can use this version. It seems that I used Gson2.4, And I still reported the error of the JsonWrite class in the Gson package when I was using it. It seems like this is the case.
Maven

1 <! -- Https://mvnrepository.com/artifact/com.squareup.retrofit2/converter-gson --> 2 <dependency> 3 <groupId> com. squareup. required fit2 </groupId> 4 <artifactId> converter-gson </artifactId> 5 <version> 2.0.1 </version> 6 </dependency> 7 <! -- Https://mvnrepository.com/artifact/com.google.code.gson/gson --> 8 <dependency> 9 <groupId> com. google. code. gson </groupId> 10 <artifactId> gson </artifactId> 11 <version> 2.6.1 </version> 12 </dependency>View Code
1 public RestClient build () {2 OkHttpClient httpClient = httpClientBuilder 3. build (); 4 return new RestClient (httpClient, 5 Response fitbuilder 6. baseUrl (baseUrl) // set URL 7. addConverterFactory (GsonConverterFactory. create () // Add Gosn converter 8. client (httpClient) 9. build () 10); 11}

 


The next step is to create an interface. Here I have written four methods for adding, deleting, modifying, and querying, and submitting Methods: GET, POST, PUT, and DELETE.

1 @Headers("Content-Type: application/json; charset=utf-8")2 @GET("{apiVersion}/saibongs/items/")3 Call<Result> search(@Path("apiVersion") String apiVersion,@Query("number")Integer number);

 

 

@ GET contains @ Query, and @ QueryMap will take the parameter? Number = 3 &.... This method is connected to the url
@ Path:
{ApiVersion}/uses/items/For example, if apiVersion = v1, its access path is v1/uses/items.

1 interface Service {2/** 3 * adds a respiratory definition record **/4 @ Headers ("Content-Type: application/json; charset = UTF-8 ") 5 @ POST ("{apiVersion}/stores/items/") 6 Call <ResponseBody> addStore (@ Path ("apiVersion") String apiVersion, @ Body StoreInfo storeInfo ); 7/** 8 * query the list of qualified repository definition records based on the parameters in the map **/9 @ Headers ("Content-Type: application/json; charset = UTF-8 ") 10 @ POST ("{apiVersion}/stores/list/") 11 Call <ResponseBody> getStoreList (@ Path ("apiVersion") String apiVersion, @ Body StoreInfo storeInfo ); 12/** 13 * modify the repository definition record */14 @ Headers ("Content-Type: application/json; charset = UTF-8 ") 15 @ PUT ("{apiVersion}/stores/items/{code}") 16 Call <ResponseBody> editStore (@ Path ("apiVersion") String apiVersion, @ Path ("code") String code, @ Body StoreInfo storeInfo); 17/** 18 * delete a repository definition record */19 @ Headers ("Content-Type: application/json; charset = UTF-8 ") 20 @ DELETE (" {apiVersion}/stores/items/{code }") 21 Call <ResponseBody> deleteStore (@ Path ("apiVersion") String apiVersion, @ Path ("code") String code); 22}View Code

 

@ Body in @ POST is bound to an object
According to the form submission method
The form submission type is @ FormUrlEncoded and corresponds to @ Field and @ FieldMap. (The form is submitted FormUrlEncoded by default)
When the form submission type is @ Multipart, it corresponds to @ Part and @ PartMap.
For example, the method I used here to query by map is to encapsulate the parameter into an object and use @ Body for normal access, I tried both of the above methods and I didn't know the reason.
You need to create one before using it.

 retrofit.create(StoreInfoService.class);    }

 

 

Then call the above method.

1/** 2 * query service directory records **/3 public List <StoreInfo> getStoreList (Catalogue catalogue, fit) throws IOException, illegalArgumentException {4 Call <ResponseBody> call = service. getStoreList (this. client. apiVersion (), catalogue); 5 List <StoreInfo> list = new ArrayList <StoreInfo> (); 6 Response <ResponseBody> bodyResponse = call.exe cute (); 7 if (bodyResponse. errorBody ()! = Null) {8 Converter <ResponseBody, ErrorMsg> errorConverter = 9 faster fit. responseBodyConverter (ErrorMsg. class, new Annotation [0]); 10 // error Type 11 ErrorMsg error = errorConverter. convert (bodyResponse. errorBody (); 12 if (error! = Null) {13 error. setStatus (bodyResponse. code () + ""); 14 throw new DataCenterException (error); 15} 16} else {17 Gson gson = new Gson (); 18 DatacenterResult datacenterResult = gson. fromJson (bodyResponse. body (). string (), new TypeToken <DatacenterResult> () {19 }. getType (); 20 PageUtil pa = datacenterResult. getPageUtil (); 21 list = pa. getList (); 22} 23 return list; 24}View Code

 

BodyResponse. body (). string () stores your result data. I used Gson to convert it into an object.
Of course, you can also directly define the type of object which can be converted by itself.

// Query service @ Headers ("Content-Type: application/json; charset = UTF-8") @ POST ("{apiVersion}/saibongs /") call <SaibongResult> searchSaibong (@ Path ("apiVersion") String apiVersion, @ Body SaibongSearch sa); public List <strong> searchSaibong (SaibongSearch saibong, descrifit fit) throws IOException, illegalArgumentException {Call <SaibongResult> call = service. searchSaibong ("v1", saibong); List <Saibong Rules> list = new ArrayList <SaibongRules> (); Response <SaibongResult> bodyResponse = call.exe cute (); // an exception manually thrown by the system, if (bodyResponse. errorBody ()! = Null) {Converter <ResponseBody, ErrorMsg> errorConverter = effecfit. responseBodyConverter (ErrorMsg. class, new Annotation [0]); // The error Type ErrorMsg is my own ErrorMsg error = errorConverter. convert (bodyResponse. errorBody (); if (error! = Null) {error. setStatus (bodyResponse. code () + ""); throw new SaibongException (error) ;}} else {SaibongResult saibongResult = bodyResponse. body (); PageUtil pa = saibongResult. getPageUtil (); list = pa. getList ();} return list ;}View Code

 


Test

A local service needs to be created for testing. Therefore, you need to add the mockwebserver jar package.
Maven

1 <dependency>2         <groupId>com.squareup.okhttp3</groupId>3         <artifactId>mockwebserver</artifactId>4         <version>3.3.1</version>5 </dependency>

Create a local service

1 MockWebServer server = new MockWebServer (); // create a local service 2 server. start (); // enable service 3 // create a connection object 4 healthy fit = new healthy fit. builder () 5. baseUrl (server. url ("/") 6. addConverterFactory (GsonConverterFactory. create () 7. build (); 8 server. enqueue (new MockResponse () 9. setResponseCode (404) // set your http status code 10 here. setBody ("here is your result set"); 11 Service service = Invalid fit. create (Service. class); 12 // call Method 13 server. add (); 14 // here we can use junit to compare the result 15 assertEquals (server. add (), "added successfully ");

 

For the first time, I want to share the things I 've made over the past few days with you --

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.