tutorial on the use of Retrofit (ii)

Source: Internet
Author: User

Query annotations

Interface queryget{@GET ("/sheet") string getString (@Query ("name") string name, @Query ("age") int of age, @QueryMap ( Encodenames=true) map<string, string> filters);}

Simulating a network request

String url= "http://tieba.baidu.com"; Restadapter Adapter =new restadapter.builder (). setEndPoint (URL). Setconverter (New Stringconverter ()). build (); Queryget Create = adapter.create (Queryget.class); Map<string,string> map=new hashmap<string, string> (), Map.put ("Gender", "male"), Map.put ("Address", "sz") ; String string = Create.getstring ("Laiqurufeng", map);
The parameters that query accesses are added after the path. The actual URL that is accessed is Http://tieba.baidu.com/sheet?name=laiqurufeng&age=22&gender=male &address=sz (simulated access) Encodenames=true means URL encoding of the URL query, as well as encodevalues. These 2 values are true by default if the above code is replaced with Map.put ("gender", "male"), and then change @querymap (Encodenames=false) then the actual access URL becomes http://tieba.baidu.com/ sheet?name=laiqurufeng&age=22& Gender =%e7%94%b7&address=sz (you can see that key is not URL-encoded and value is URL-encoded).
field and part annotationswe can also send Form-data and multipart-data at the POST request.@formurlencoded annotations are used for form data. Each pair of key-value pairs is annotated with @field, including the value of the first name and value object.
@FormUrlEncoded @post ("/user/edit") User UpdateUser (@Field ("First_Name") string first, @Field ("Last_Name") string last );

Use @multipart annotations to send Multipart-data, each part with a @part annotation.

@Multipart @put ("/user/photo") User UpdateUser (@Part ("photo") Typedfile photo, @Part ("description") typedstring Description);

Header AnnotationsHeader is divided into key and value are fixed, static header annotation method and dynamic header annotation method
Interface fixedheader{@Headers ({                                          //static header    "Accept:application/vnd.github.v3.full+json",    " User-agent:retrofit-sample-app "}) @GET ("/")                      Response getResponse ();}

Dynamic Header

Interface dynamicheader{@Headers ("cache-control:max-age=640000")             //Static Header@get ("/") Response GetResponse (@ Header ("Header1") string header1, @Header ("Header2") string header2);//dynamic Header whose value can be dynamically passed in when this method is called.}

Synchronous and asynchronousThe method that has the return value is executed synchronously.
@GET ("/user/{id}/photo") Photo Getuserphoto (@Path ("id") int id);

If you want to use asynchronous execution, the last parameter to the method is callback.

Interface asychronousclient{@GET ("/") void GetResponse (callback<string> Callback);  If you use async, pay special attention to the return value of the method here must be void,response to the object type written in the callback<> generic.}
On the Android platform, the statements in callbacks are executed on the main thread. (the part of the network access is executed in the child thread), and if it is a desktop application, the thread that callbacks executes the thread and the HTTP access is the same thread. If the method is asynchronous and the return value is not void, The following exception is thrown at run time. Java.lang.IllegalArgumentException:xxx must has a return type or Callback as last argument, not both. The following code can be directly Run in the main thread.
Restadapter adapter=new Restadapter.builder (). setEndPoint ("http://www.baidu.com"). Setconverter (New Stringconverter ()). build (); Asychronousclient Create = adapter.create (Asychronousclient.class); Create.getresponse (new callback<string> () {@Override public void Success (String str, Response Response) {   ///The first parameter is a string that is implemented by our own Stringconverter Response Converted to a string. Execution when the access succeeds} @Override public void failure (Retrofiterror paramretrofiterror) {//access fails, for example, the return code is 40x, 50x or IO exception}});

  

 

tutorial on the use of Retrofit (ii)

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.