Android經常使用的網絡訪問HttpClient, HttpUrlConnection,OkHttp(okgo),xUtils, Volley等. Android4.4以後使用OkHttp做爲HttpUrlConnection底層實現。此次講一下Retrofit2怎麼使用。java
Retrofit2其實是經過註解的方式對okhttp又一次封裝。android
在AndroidStudio項目中,添加Retrofit2的依賴。git
compile 'com.squareup.retrofit2:retrofit:2.3.0' github
程序構建成功後,查看項目具體依賴了多少jar包。緩存
com.squareup.okhttp3:okhttp:3.8.0 com.squareup.okio:okio:1.13.0 com.squareup.retrofit2:retrofit:2.3.0
retrofit2 強制依賴了okhttp3的相關庫。這也說明了retrofit2底層是okhttp3具體實現的。okhttp3是用來具體訪問網絡的,okio是squareup對Java的io/nio的補充,使其更容易訪問,存儲和處理數據。okio主要功能封裝到了ByteString和Buffer裏面了。服務器
2.1. 首先實例化okhttp網絡
OkHttpClient client = new OkHttpClient.Builder().build(); //實例化OkHttpClient的時候,還能夠設置攔截器,緩存,認證信息,網絡攔截器,鏈接池,超時時間等信息。
2.2. 其次實例化retrofit,並將實例化好的okhttp3關聯到retrofit2。框架
Retrofit retrofit = new Retrofit.Builder().client(client).baseUrl("https://suggest.taobao.com/").build();
2.2.1 ...build()方法:ide
public Retrofit build() { if (baseUrl == null) { throw new IllegalStateException("Base URL required."); } okhttp3.Call.Factory callFactory = this.callFactory; if (callFactory == null) { callFactory = new OkHttpClient(); } Executor callbackExecutor = this.callbackExecutor; if (callbackExecutor == null) { callbackExecutor = platform.defaultCallbackExecutor(); } // Make a defensive copy of the adapters and add the default Call adapter. List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories); adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor)); // Make a defensive copy of the converters. List<Converter.Factory> converterFactories = new ArrayList<>(this.converterFactories); return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories, callbackExecutor, validateEagerly); }
從這個方法裏面能夠看出,在實例化Retrofit的時候,baseUrl這個變量是必需要設置的,不然直接拋出IllegalStateException;而其他的一些信息若是不進行,程序裏面會給設置一個默認的信息.默認給設置了OkHttpClient實例,OkHttp3鏈接池、解析工廠、CallAdapter等信息;而後返回了一個retrofit2實例。工具
2.3. 定義接口文件ApiService。
interface ApiService{ @GET("sug?code=utf-8&q=java&callback=cb") Call<ResponseBody> getGithubApi(); }
定義一個接口信息。Retrofit2中訪問的一個網絡接口,返回的都是一個Call<ResponseBody> 實例,準確的說是Call<T>實例,可是這個實例中並無在實例化Retrofit2中設置addConverterFactory方法,若是須要解析成具體的JavaBean,則又須要依賴 'com.squareup.retrofit2:converter-gson:2.0.2', 'com.google.code.gson:gson:2.3.1'。固然再配合rxjava,rxandroid來使用的話,將是Android平臺很流行的網絡訪問框架,三者的整合封裝本文不講。
Retrofit2中支持多種註解來定義http網絡訪問,好比:POST,GET,DELETE,PUT;還支持多種標記註解FormUrlEncoded(使用到的註解都放到了retrofit2.http包下)
已2.3 ApiService接口爲例。這個接口中定義了一個getGithubApi方法,該方法使用get方式提交,具體的路徑則寫到@GET("sug?code=utf-8&q=java&callback=cb"),咱們知道get方式提交參數是直接將參數拼接到url地址後面。一樣也可使用POST註解,表示該表單使用POST方式提交參數,要提交的參數則須要傳入到方法裏面了,該方法就應該這麼定義getGithubApi(@Field("code") String code,@Field("q") String q,@Field("callback") String callback)或者getGithubApi(@FieldMap Map<String, String> params)//其中params的key做爲參數名,value做爲參數的值。
經常使用的註解表格
標記在方法名之上 序號 |
名稱 | 備註 |
---|---|---|
1 | GET | 表示該方法使用GET方式提交參數。 |
2 | POST | 表示該方法使用POST方式提交參數,這個常常和參數標記@Field和@FieldMap組合使用,也配合方法標記@FormUrlEncoded使用。 |
3 | PUT | |
4 | DELETE | |
5 | PATCH | |
6 | HEAD | |
7 | OPTIONS | |
8 | HTTP | 更加靈活的標記,這個標記裏面能夠指定,提交方式,path值,是否有body。 |
9 | Streaming | 返回流數據,當服務器返回的數據過大時使用 |
好比:使用HTTP註解
@HTTP(method = "get", path = "zzhhz/{id}", hasBody = false) Call<ResponseBody> getBlog(@Path("id") int id);
這裏面指定了提交方式,path路徑,是否有body體。在這個地方path="zzhhz/{id}",id是不肯定的,又要當一個參數傳進去,用{}標記變量,而後使用Path註解標記在方法形參前。
標記在形參以前:
序號 | 名稱 | 備註 |
---|---|---|
1 | Field/FieldMap | 這個參數註解常常配合POST註解使用,由於POST是隱式提交參數。 |
2 | Part/PartMap | 這個常常是表示提交文件,又和Multipart,POST註解配合使用。 |
3 | Path | url路徑,如上邊HTTP註解示例 |
4 | Query/QueryMap/QueryName | 查詢參數,一般配合GET註解使用 |
2.4. 訪問數據。
ApiService githubService = retrofit.create(ApiService.class); Call<ResponseBody> githubApi = githubService.getGithubApi(); Response<ResponseBody> execute = githubApi.execute(); if (execute != null && execute.isSuccessful()){ String string = execute.body().string(); System.out.println(string); } else { System.out.println("訪問失敗"); }
以前說過Retrofit2強制依賴了OkHttp3, 在2.2實例化Retrofit2的時候,將已實例化的OkHttpClient傳入進Retrofit2裏,供其進行網絡訪問。
Retrofit2和OkHttp3實例化過程當中使用到了建造者模式(不贅述涉及模式)。
完整的網絡訪問設置:添加上攔截器(基於Java項目,開發工具IDEA)。
@Test
public void testRetrofit() throws IOException {
//https://suggest.taobao.com/sug?code=utf-8&q=java&callback=cb
OkHttpClient client = new OkHttpClient.Builder().addInterceptor((chain) -> { Request request = chain.request(); return chain.proceed(request); }).readTimeout(60, TimeUnit.SECONDS).writeTimeout(60, TimeUnit.SECONDS).build(); Retrofit retrofit = new Retrofit.Builder().client(client).baseUrl("https://suggest.taobao.com/").build(); ApiService githubService = retrofit.create(ApiService.class); Call<ResponseBody> githubApi = githubService.getGithubApi(); Response<ResponseBody> execute = githubApi.execute(); if (execute != null && execute.isSuccessful()) { String string = execute.body().string(); System.out.println(string); } else { System.out.println("訪問失敗"); }
}
interface ApiService {br/>@GET("sug?code=utf-8&q=java&callback=cb")
Call<ResponseBody> getGithubApi();
}
到此Retrofit2講解完畢。語言組織的很差,有什麼問題你們能夠留言,相互學習。