您好,登錄后才能下訂單哦!
Android常用的網(wǎng)絡(luò)訪問HttpClient, HttpUrlConnection,OkHttp(okgo),xUtils, Volley等. Android4.4之后使用OkHttp作為HttpUrlConnection底層實(shí)現(xiàn)。這次講一下Retrofit2怎么使用。
Retrofit2實(shí)際上是通過注解的方式對okhttp又一次封裝。
在AndroidStudio項(xiàng)目中,添加Retrofit2的依賴。
compile 'com.squareup.retrofit2:retrofit:2.3.0'
程序構(gòu)建成功后,查看項(xiàng)目具體依賴了多少jar包。
com.squareup.okhttp3:okhttp:3.8.0
com.squareup.okio:okio:1.13.0
com.squareup.retrofit2:retrofit:2.3.0
retrofit2 強(qiáng)制依賴了okhttp3的相關(guān)庫。這也說明了retrofit2底層是okhttp3具體實(shí)現(xiàn)的。okhttp3是用來具體訪問網(wǎng)絡(luò)的,okio是squareup對Java的io/nio的補(bǔ)充,使其更容易訪問,存儲和處理數(shù)據(jù)。okio主要功能封裝到了ByteString和Buffer里面了。
2.1. 首先實(shí)例化okhttp
OkHttpClient client = new OkHttpClient.Builder().build();
//實(shí)例化OkHttpClient的時候,還可以設(shè)置攔截器,緩存,認(rèn)證信息,網(wǎng)絡(luò)攔截器,連接池,超時時間等信息。
2.2. 其次實(shí)例化retrofit,并將實(shí)例化好的okhttp3關(guān)聯(lián)到retrofit2。
Retrofit retrofit = new Retrofit.Builder().client(client).baseUrl("https://suggest.taobao.com/").build();
2.2.1 ...build()方法:
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);
}
從這個方法里面可以看出,在實(shí)例化Retrofit的時候,baseUrl這個變量是必須要設(shè)置的,否則直接拋出IllegalStateException;而其余的一些信息如果不進(jìn)行,程序里面會給設(shè)置一個默認(rèn)的信息.默認(rèn)給設(shè)置了OkHttpClient實(shí)例,OkHttp3連接池、解析工廠、CallAdapter等信息;然后返回了一個retrofit2實(shí)例。
2.3. 定義接口文件ApiService。
interface ApiService{
@GET("sug?code=utf-8&q=java&callback=cb")
Call<ResponseBody> getGithubApi();
}
定義一個接口信息。Retrofit2中訪問的一個網(wǎng)絡(luò)接口,返回的都是一個Call<ResponseBody> 實(shí)例,準(zhǔn)確的說是Call<T>實(shí)例,但是這個實(shí)例中并沒有在實(shí)例化Retrofit2中設(shè)置addConverterFactory方法,如果需要解析成具體的JavaBean,則又需要依賴 'com.squareup.retrofit2:converter-gson:2.0.2', 'com.google.code.gson:gson:2.3.1'。當(dāng)然再配合rxjava,rxandroid來使用的話,將是Android平臺很流行的網(wǎng)絡(luò)訪問框架,三者的整合封裝本文不講。
Retrofit2中支持多種注解來定義http網(wǎng)絡(luò)訪問,比如:POST,GET,DELETE,PUT;還支持多種標(biāo)記注解FormUrlEncoded(使用到的注解都放到了retrofit2.http包下)
已2.3 ApiService接口為例。這個接口中定義了一個getGithubApi方法,該方法使用get方式提交,具體的路徑則寫到@GET("sug?code=utf-8&q=java&callback=cb"),我們知道get方式提交參數(shù)是直接將參數(shù)拼接到url地址后面。同樣也可以使用POST注解,表示該表單使用POST方式提交參數(shù),要提交的參數(shù)則需要傳入到方法里面了,該方法就應(yīng)該這么定義getGithubApi(@Field("code") String code,@Field("q") String q,@Field("callback") String callback)或者getGithubApi(@FieldMap Map<String, String> params)//其中params的key作為參數(shù)名,value作為參數(shù)的值。
常用的注解表格
標(biāo)記在方法名之上 序號 |
名稱 | 備注 |
---|---|---|
1 | GET | 表示該方法使用GET方式提交參數(shù)。 |
2 | POST | 表示該方法使用POST方式提交參數(shù),這個經(jīng)常和參數(shù)標(biāo)記@Field和@FieldMap組合使用,也配合方法標(biāo)記@FormUrlEncoded使用。 |
3 | PUT | |
4 | DELETE | |
5 | PATCH | |
6 | HEAD | |
7 | OPTIONS | |
8 | HTTP | 更加靈活的標(biāo)記,這個標(biāo)記里面可以指定,提交方式,path值,是否有body。 |
9 | Streaming | 返回流數(shù)據(jù),當(dāng)服務(wù)器返回的數(shù)據(jù)過大時使用 |
比如:使用HTTP注解
@HTTP(method = "get", path = "zzhhz/{id}", hasBody = false)
Call<ResponseBody> getBlog(@Path("id") int id);
這里面指定了提交方式,path路徑,是否有body體。在這個地方path="zzhhz/{id}",id是不確定的,又要當(dāng)一個參數(shù)傳進(jìn)去,用{}標(biāo)記變量,然后使用Path注解標(biāo)記在方法形參前。
標(biāo)記在形參之前:
序號 | 名稱 | 備注 |
---|---|---|
1 | Field/FieldMap | 這個參數(shù)注解經(jīng)常配合POST注解使用,因?yàn)镻OST是隱式提交參數(shù)。 |
2 | Part/PartMap | 這個經(jīng)常是表示提交文件,又和Multipart,POST注解配合使用。 |
3 | Path | url路徑,如上邊HTTP注解示例 |
4 | Query/QueryMap/QueryName | 查詢參數(shù),通常配合GET注解使用 |
2.4. 訪問數(shù)據(jù)。
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強(qiáng)制依賴了OkHttp3, 在2.2實(shí)例化Retrofit2的時候,將已實(shí)例化的OkHttpClient傳入進(jìn)Retrofit2里,供其進(jìn)行網(wǎng)絡(luò)訪問。
Retrofit2和OkHttp3實(shí)例化過程中使用到了建造者模式(不贅述涉及模式)。
完整的網(wǎng)絡(luò)訪問設(shè)置:添加上攔截器(基于Java項(xiàng)目,開發(fā)工具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 {@GET("sug?code=utf-8&q=java&callback=cb")
br/>@GET("sug?code=utf-8&q=java&callback=cb")
}
到此Retrofit2講解完畢。語言組織的不好,有什么問題大家可以留言,相互學(xué)習(xí)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。