RETROFIT2 official release has a period of time, the official also just out of 2.0beta version of the time to replace the official website, so use retrofit, we also do not tangle it with the previous version of the difference, from the 2.0 version of the beginning of it.
Introduced
Using the Android Studio development tool, introduce the following:
‘com.squareup.retrofit2:retrofit:2.0.2‘ ‘com.squareup.okhttp3:okhttp:3.2.0‘ ‘com.squareup.retrofit2:converter-gson:2.0.2‘
Retrofit supports Rxjava, so I'm going to write another example of Rxjava, which is a comparison with normal use. So go into these libraries (don't introduce the following three libraries if you don't know Rxjava):
‘io.reactivex:rxjava:1.1.3‘ ‘io.reactivex:rxandroid:1.1.0‘ ‘com.squareup.retrofit2:adapter-rxjava:2.0.2‘
Interface class
First look at a simple effect, enter the ID number, determine the validity of the ID card number, the output of the person's birthday:
function is very simple, interface I use the aggregated data provided by the identity query API, the main implementation of the following methods.
Let's start by showing this URL:
http://apis.juhe.cn/idcard/index?key=您申请的KEY&cardno=330326198903081211
First, an interface (interface) is required to encapsulate this URL:
publicinterface PersonApi { @GET("index") Call<PersonPojo> getPersonCardNum(@Query("key"@Query("cardno") String num);}
For friends who have not contacted retrofit, here are some explanations:
@GET ("index")
The delegate uses the Get method request, and index is part of the question mark in the above URL, followed by the previous section.
@Query
Represents access to this URL parameter, which means that access to this URL requires two parameters, one is the access to use the secret key, one is the ID number.
Call<PersonPojo>
This is the return value that has parsed the JSON into an entity.
Network Engine class
Then you need a network engine class, which puts the access to the data, first of all the construction method is written inside:
public class Net { Span class= "Hljs-keyword" >private static personapi Personapi; private static Okhttpclient okhttpclient = new okhttpclient (); private static Converter.factory gsonconverterfactory = Gsonconverterfactory.create (); public net () {Retrofit Retrofit = new retrofit.builder (). Client (Okhttpclien T). BASEURL ( "http://apis.juhe.cn/idcard/" ). Addconverterfac Tory (Gsonconverterfactory). build (); Personapi = Retrofit.create (Personapi.class); }
Okhttpclient is the underlying network access tool, Gsonconverterfactory.create () means an instance of the internal JSON parsing tool Gson. In BaseURL, the first half of the URL above is actually the URL of the host we use.
Then there is the way to write the data:
Public void Getpseroncardnum(String num,FinalOncheckcardlistener Oncheckcardlistener) {call<personpojo> call = Personapi.getpersoncardnum ("Fe15ed66cfb72823024958f4b1dc50e7", num); Call.enqueue (NewCallback<personpojo> () {@Override Public void Onresponse(call<personpojo> call, response<personpojo> Response) {oncheckcardlistener.onsuccess (Response.body ()); }@Override Public void onfailure(call<personpojo> call, Throwable t) {Oncheckcardlistener.onerror ("Error"); System.out.println ("Err"); } }); }
Oncheckcardlistener is a callback interface for activity. If it succeeds, the parsed entity is passed out, and if it fails, the string "error" is simple and straightforward.
Then look at the activity:
Public class mainactivity extends appcompatactivity implements Oncheckcardlistener{TextView Card,result; Button check; NET net;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); NET =NewNet (); Card = (TextView) Findviewbyid (R.id.tv_card); result = (TextView) Findviewbyid (R.id.tv_result); Check = (Button) Findviewbyid (R.id.btn_check); Check.setonclicklistener (NewView.onclicklistener () {@Override Public void OnClick(View v) {Net.getpseroncardnum (Card.gettext (). toString (), mainactivity. This); } }); }@Override Public void onsuccess(Personpojo Personpojo) {if(Personpojo.getresultcode (). Equals (" the") {Result.settext (Personpojo.getresult (). Getbirthday ()); }Else{Result.settext (Personpojo.getresultcode ()); } }@Override Public void OnError(String msg) {Result.settext (msg); }}
This is the use of Retrofit2 do simple function, just for the sake of getting started, in fact, there are many functions retrofit, in terms of parameters, such as access to the RESTful URL when the use of @path, as well as the entity as the parameters used to @body and so on.
Returning entities that support Rxjava
The following section is for the above function with Rxjava implementation, the function has not changed, so paste the code directly.
publicinterface PersonApi { @GET("index") Call<PersonPojo> getPersonCardNum(@Query("key"@Query("cardno") String num); @GET("index") Observable<PersonPojo> getPersonCardNum2(@Query("key"@Query("cardno") String num);}
Network Engine class, Net.java:
Public class Net { Private StaticPersonapi Personapi;Private StaticOkhttpclient okhttpclient =NewOkhttpclient ();Private StaticConverter.factory gsonconverterfactory = Gsonconverterfactory.create ();Private StaticCalladapter.factory rxjavacalladapterfactory = Rxjavacalladapterfactory.create (); Public Net() {Retrofit Retrofit =NewRetrofit.builder (). Client (okhttpclient). BASEURL ("http://apis.juhe.cn/idcard/"). Addconverterfactory (Gsonconverterfactory). Addcalladapterfactory (rxjavacalladapterfactory ). build (); Personapi = Retrofit.create (Personapi.class); } Public void Getpseroncardnum(String num,FinalOncheckcardlistener Oncheckcardlistener) {call<personpojo> call = Personapi.getpersoncardnum ("Fe15ed66cfb72823024958f4b1dc50e7", num); Call.enqueue (NewCallback<personpojo> () {@Override Public void Onresponse(call<personpojo> call, response<personpojo> Response) {oncheckcardlistener.onsuccess (Response.body ()); }@Override Public void onfailure(call<personpojo> call, Throwable t) {Oncheckcardlistener.onerror ("Error"); System.out.println ("Err"); } }); } Public void getPseronCardNum2(String num,FinalOncheckcardlistener oncheckcardlistener) {observable<personpojo> Observable = personapi.getpersoncardnum2 ("Fe15ed66cfb72823024958f4b1dc50e7", num); Observable.subscribeon (Schedulers.io ()). Observeon (Androidschedulers.mainthread ()). Subscribe (NewSubscriber<personpojo> () {@Override Public void oncompleted() {System.out.println ("Complete"); }@Override Public void OnError(Throwable e) {Oncheckcardlistener.onerror ("Error"); System.out.println ("Err"); }@Override Public void OnNext(Personpojo Personpojo) {oncheckcardlistener.onsuccess (Personpojo); } }); }}
The others are the same, and there are projects above that can be downloaded.
Download point here
Retrofit2 Simple to use