標籤:ide 請求方式 中斷 .exe body cal 訪問 use ase
1、依賴 build.gradle
compile ‘com.squareup.retrofit2:retrofit:2.1.0‘compile ‘com.squareup.retrofit2:converter-gson:2.1.0‘
2、許可權
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
3、擷取api資料的地址,我從網上找了一個擷取天氣的地址,如下:
https://www.apiopen.top/weatherApi?city=海口
看這個地址就是可以用get方法來擷取。
以上這些準備好了,我們就開始Retrofit的學習,剛開始我也是摸不著頭髮,感覺好深奧,可能是菜鳥的原因,決定從最基礎的入手。
首先我建立一個介面:擷取天氣的api
WeatherApi.class
public interface WeatherApi { @GET("weatherApi?city=海口") Call<ResponseBody> getWeatherInfo();}
Retrofit提供的請求方式註解有@GET和@POST等,分別代表GET請求和POST請求,上面用的是GET請求,訪問的地址是:“weatherApi?city=海口”。另外定義getWeahterInfo()方法,這個方法返回的類型Call<ResponseBody>。
然後我們建立Retroit
Retrofit retrofit = new Retrofit.Builder.baseUrl("https://www.apiopen.top/").addConverterFactory(GsonConverterFactory.create()).build();WeatherApi weatherApi = retrofit.create(WeatherApi.class);Call<ResponseBody> call = weatherApi.getWeatherInfo();
Retrofit是通過建造者模式構建出來的,請求的url是拼接而成,它是由baseUrl傳入的URL加上請求網路介面的@GET("weatherApi?city=海口")中的URL拼接而成的,接下來用Retrofit的create方法動態代理擷取到之前定義的介面,並調用該介面定義的getWeatherInfo()方法得到Call對象。 接下來用Call請求網路並處理回調,代碼如下:
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) { } });
請求是異地請求網路,回調的CallBack是運行在UI線程,得到返回的response.body()就是一個json串,我們用string()列印出來,用Toast顯示看看。如果想同步,請用call.execute();如果想中斷網路,請用call.cancel()。
如有轉載,請表明出處
【原創】Android Retrofit學習之旅