【原創】Android Retrofit學習之旅

來源:互聯網
上載者:User

標籤: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學習之旅

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.