1. Reliance on Build.gradle
compile ‘com.squareup.retrofit2:retrofit:2.1.0‘compile ‘com.squareup.retrofit2:converter-gson:2.1.0‘
2. Permissions
Androidmanifest.xml
<uses-permission android:name="android.permission.INTERNET" />
3, get the address of the API data, I found a Web site to get the weather address, as follows:
https://www.apiopen.top/weatherApi?city=海口
Look at this address can be obtained using the Get method.
These are ready, we began to retrofit study, just at the beginning I also can not touch the hair, feel good abstruse, may be rookie reason, decided from the most basic start.
First I create a new interface: Get the Weather API
Weatherapi.class
public interface WeatherApi { @GET("weatherApi?city=海口") Call<ResponseBody> getWeatherInfo();}
Retrofit provides the request way annotation has @get and @post, respectively represents the GET request and the POST request, above uses the GET request, the access address is: "Weatherapi?city= Haikou". Also define the Getweahterinfo () method, which returns the type call<responsebody>.
Then we create the Retroit
new Retrofit.Builder.baseUrl("https://www.apiopen.top/").addConverterFactory(GsonConverterFactory.create()).build();WeatherApi weatherApi = retrofit.create(WeatherApi.class);Call<ResponseBody> call = weatherApi.getWeatherInfo();
Retrofit is built by the builder pattern, the requested URL is stitched together, it is by the BaseURL incoming URL plus the request network interface @get ("weatherapi?city= Haikou") in the URL stitching, Next, using the retrofit create method, the dynamic proxy obtains the previously defined interface and invokes the Getweatherinfo () method defined by the interface to get the call object. Next, use call to request the network and process the callback with the following code:
call.enqueue (new Callback< Responsebody> () { @Override public void onresponse (call<responsebody> call, response<responsebody> Response) { String body = null; try {body = Response. Body (). string (); catch (IOException e) {e.printstacktrace ();} Toastutils.showlong (body);} @Override public void onFailure ( Call<responsebody> call, Throwable t) {}});
The request is an off-site request network, the callback callback is run on the UI thread, the returned Response.body () is a JSON string, we print it with a string (), and look at the toast display. If you want to sync, use Call.execute (), or if you want to interrupt the network, use Call.cancel ().
If reproduced, please indicate the source
"Original" Android Retrofit Learning Tour