Tutorial on using retrofit (i)

Source: Internet
Author: User
Tags maven central

This tutorial is based on the retrofit1.9 version and Android platform. Prepare:Retrofit: Https://github.com/square/retrofitIf you introduce a jar package, you also introduce additional retrofit dependent jar packages.Because the retrofit1.9 version no longer supports Android native URLConnection and httpclient frameworks. The okHttp2.0 framework must be introduced for network access. The following 2 are necessary jar packages OKHTTP-2.2.0.JAROKIO-1.0.2.J AR (Okhttp's dependent jar package) The following Jar is a feature-enhanced jar package. Based on the features you want to use, go to the. Gson-2.3.jarappengine-api-1.0-sdk-1.9.12.jarrxjava-1.0.0.jar above jar packages can be downloaded at github or Maven central repository. Note The version of the Italian jar package. Get mode
Interface simpleget{@GET ("/")//indicates a GET mode.  "/" will be stitched up behind the URL (host address) in the setEndPoint (URL). Response GetResponse (); It can be simply understood that the response is converted to an object after the network access. There is no conversion, or response.}
Access, note on Android to execute the following statement on an asynchronous thread.
String url= "http://tieba.baidu.com"; Restadapter adapter=new Restadapter.builder (). setEndPoint (URL). build (); setEndPoint (URL) sets the host address of the network access address simpleget create = adapter.create (Simpleget.class); Retrofit generates an instance of the above Simpleget interface. Response Response = Create.getresponse (); int status = Response.getstatus (); Return code try {InputStream in = Response.getbody (). in (); the input stream of the//response. See the input stream for network access is familiar. Want to convert to a string or json or a picture to see what the server gave. catch (IOException e) {e.printstacktrace ();}

  

Post Mode
Interface simplepost{@POST ("/android")//indicates that access is made using POST. And the back path is stitched to the back of the hostname--stitching to the back of the URL in the setEndPoint (URL). Response getResponse ();}
Executes the following statement in an asynchronous thread.
String url= "http://tieba.baidu.com"; Restadapter adapter=new Restadapter.builder (). setEndPoint (URL). build (); and the path stitching on the back of the above post, want to access Http://tieba.baidu.com/androidSimplePOST Create = Adapter.create (Simplepost.class); Response Response = Create.getresponse (); int status = Response.getstatus (); try {inputstream in = Response.getbody (). In () ;} catch (IOException e) {e.printstacktrace ();}
PATHpath can be dynamically replaced.
Interface GitHub {@GET ("/repos/{owner}/{repo}/contributors") list<contributor> Contributors (@Path ("owner") String owner, @Path ("repo") string repo);
Network Access section
private static final String Api_url = "https://api.github.com"; Restadapter restadapter = new Restadapter.builder (). setEndPoint (Api_url). build (); GitHub github = restadapter.create (Github.class); List<contributor> contributors = Github.contributors ("Square", "retrofit"); Equivalent to dynamic substitution of the {} part of the path. Equivalent to access https://api.github.com/repos/square/retrofit/contributors

  

Gsonconverter the default converterSee above these some, can recall retrofit also no convenient how many ah. Here's an example of how retrofit's charm lies.
Static class Contributor {//A Pojo class (Plain ordinary Java object) Simple Java objects--and simpler than JavaBean.  String login; int contributions;} Interface GitHub {@GET ("/repos/{owner}/{repo}/contributors") list<contributor> Contributors (@Path ("owner") String owner, @Path ("repo") string repo);
Network Access section.
Restadapter restadapter = new Restadapter.builder (). setEndPoint (Api_url). build (); The Gsonconverter Converter is set by default. Parses response directly into a Pojo object. GitHub GitHub = restadapter.create (Github.class);// Access to this address returns a Jsonarray,jsonarray each element has login and contributions the 2 keys and their corresponding value. Extracted and encapsulated into the Pojo object. List<contributor > contributors = github.contributors ("Square", "retrofit");  For (contributor contributor:contributors) {LOG.V ("retrofit", Contributor.login + "(" + contributor.contributions + ")" );}

 

Custom Converter (stringconverter)Response can get the input stream, we can convert it to any desired format. Custom StringconverterConverters
Class Stringconverter implements converter{@Override public Object frombody (typedinput input, type type) throws Conver    String str = convertstream2string (in);  return str;  } catch (IOException e) {e.printstacktrace ();  } return null; } private String Convertstream2string (InputStream in) throws IOException {//inputstream converted to String BufferedReader reader=  New BufferedReader (New InputStreamReader (in));  StringBuilder sb=new StringBuilder ();  String Line=null;    while ((Line=reader.readline ())!=null) {sb.append (line);  Sb.append ("\ n"); } return Sb.tostring ();} @Overridepublic typedoutput tobody (Object obj) {//objects to output stream conversion return null;}}
Interface Stringclient {@GET ("/") string getString ();//The return value of the method is string, Requires the Stringconverter Converter converter to convert response to string.}
Asynchronous thread Invocation

  

Tutorial on using retrofit (i)

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.