欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

Retrofit2的使用

Retrofit2

Android常用的網(wǎng)絡(luò)訪問(wèn)HttpClient, HttpUrlConnection,OkHttp(okgo),xUtils, Volley等. Android4.4之后使用OkHttp作為HttpUrlConnection底層實(shí)現(xiàn)。這次講一下Retrofit2怎么使用。

十多年的漢川網(wǎng)站建設(shè)經(jīng)驗(yàn),針對(duì)設(shè)計(jì)、前端、開(kāi)發(fā)、售后、文案、推廣等六對(duì)一服務(wù),響應(yīng)快,48小時(shí)及時(shí)工作處理。營(yíng)銷(xiāo)型網(wǎng)站的優(yōu)勢(shì)是能夠根據(jù)用戶(hù)設(shè)備顯示端的尺寸不同,自動(dòng)調(diào)整漢川建站的顯示方式,使網(wǎng)站能夠適用不同顯示終端,在瀏覽器中調(diào)整網(wǎng)站的寬度,無(wú)論在任何一種瀏覽器上瀏覽網(wǎng)站,都能展現(xiàn)優(yōu)雅布局與設(shè)計(jì),從而大程度地提升瀏覽體驗(yàn)。成都創(chuàng)新互聯(lián)公司從事“漢川網(wǎng)站設(shè)計(jì)”,“漢川網(wǎng)站推廣”以來(lái),每個(gè)客戶(hù)項(xiàng)目都認(rèn)真落實(shí)執(zhí)行。

Retrofit2實(shí)際上是通過(guò)注解的方式對(duì)okhttp又一次封裝。

  1. 在AndroidStudio項(xiàng)目中,添加Retrofit2的依賴(lài)。

    compile 'com.squareup.retrofit2:retrofit:2.3.0'

程序構(gòu)建成功后,查看項(xiàng)目具體依賴(lài)了多少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)制依賴(lài)了okhttp3的相關(guān)庫(kù)。這也說(shuō)明了retrofit2底層是okhttp3具體實(shí)現(xiàn)的。okhttp3是用來(lái)具體訪問(wèn)網(wǎng)絡(luò)的,okio是squareup對(duì)Java的io/nio的補(bǔ)充,使其更容易訪問(wèn),存儲(chǔ)和處理數(shù)據(jù)。okio主要功能封裝到了ByteString和Buffer里面了。

  1. 簡(jiǎn)單的網(wǎng)絡(luò)訪問(wèn)(以https://suggest.taobao.com/sug?code=utf-8&q=java&callback=cb為例)。

2.1. 首先實(shí)例化okhttp

    OkHttpClient client = new OkHttpClient.Builder().build();
//實(shí)例化OkHttpClient的時(shí)候,還可以設(shè)置攔截器,緩存,認(rèn)證信息,網(wǎng)絡(luò)攔截器,連接池,超時(shí)時(shí)間等信息。

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);
}

從這個(gè)方法里面可以看出,在實(shí)例化Retrofit的時(shí)候,baseUrl這個(gè)變量是必須要設(shè)置的,否則直接拋出IllegalStateException;而其余的一些信息如果不進(jìn)行,程序里面會(huì)給設(shè)置一個(gè)默認(rèn)的信息.默認(rèn)給設(shè)置了OkHttpClient實(shí)例,OkHttp3連接池、解析工廠、CallAdapter等信息;然后返回了一個(gè)retrofit2實(shí)例。

2.3. 定義接口文件ApiService。

interface ApiService{
    @GET("sug?code=utf-8&q=java&callback=cb")
    Call<ResponseBody> getGithubApi();
}

定義一個(gè)接口信息。Retrofit2中訪問(wèn)的一個(gè)網(wǎng)絡(luò)接口,返回的都是一個(gè)Call<ResponseBody> 實(shí)例,準(zhǔn)確的說(shuō)是Call<T>實(shí)例,但是這個(gè)實(shí)例中并沒(méi)有在實(shí)例化Retrofit2中設(shè)置addConverterFactory方法,如果需要解析成具體的JavaBean,則又需要依賴(lài) 'com.squareup.retrofit2:converter-gson:2.0.2', 'com.google.code.gson:gson:2.3.1'。當(dāng)然再配合rxjava,rxandroid來(lái)使用的話,將是Android平臺(tái)很流行的網(wǎng)絡(luò)訪問(wèn)框架,三者的整合封裝本文不講。

Retrofit2中支持多種注解來(lái)定義http網(wǎng)絡(luò)訪問(wèn),比如:POST,GET,DELETE,PUT;還支持多種標(biāo)記注解FormUrlEncoded(使用到的注解都放到了retrofit2.http包下)

已2.3 ApiService接口為例。這個(gè)接口中定義了一個(gè)getGithubApi方法,該方法使用get方式提交,具體的路徑則寫(xiě)到@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)記在方法名之上
序號(hào)
名稱(chēng)備注
1 GET 表示該方法使用GET方式提交參數(shù)。
2 POST 表示該方法使用POST方式提交參數(shù),這個(gè)經(jīng)常和參數(shù)標(biāo)記@Field和@FieldMap組合使用,也配合方法標(biāo)記@FormUrlEncoded使用。
3 PUT
4 DELETE
5 PATCH
6 HEAD
7 OPTIONS
8 HTTP 更加靈活的標(biāo)記,這個(gè)標(biāo)記里面可以指定,提交方式,path值,是否有body。
9 Streaming 返回流數(shù)據(jù),當(dāng)服務(wù)器返回的數(shù)據(jù)過(guò)大時(shí)使用

比如:使用HTTP注解

@HTTP(method = "get", path = "zzhhz/{id}", hasBody = false)
Call<ResponseBody> getBlog(@Path("id") int id);

這里面指定了提交方式,path路徑,是否有body體。在這個(gè)地方path="zzhhz/{id}",id是不確定的,又要當(dāng)一個(gè)參數(shù)傳進(jìn)去,用{}標(biāo)記變量,然后使用Path注解標(biāo)記在方法形參前。

標(biāo)記在形參之前:

序號(hào)名稱(chēng)備注
1 Field/FieldMap 這個(gè)參數(shù)注解經(jīng)常配合POST注解使用,因?yàn)镻OST是隱式提交參數(shù)。
2 Part/PartMap 這個(gè)經(jīng)常是表示提交文件,又和Multipart,POST注解配合使用。
3 Path url路徑,如上邊HTTP注解示例
4 Query/QueryMap/QueryName 查詢(xún)參數(shù),通常配合GET注解使用

2.4. 訪問(wèn)數(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("訪問(wèn)失敗");
}

之前說(shuō)過(guò)Retrofit2強(qiáng)制依賴(lài)了OkHttp3, 在2.2實(shí)例化Retrofit2的時(shí)候,將已實(shí)例化的OkHttpClient傳入進(jìn)Retrofit2里,供其進(jìn)行網(wǎng)絡(luò)訪問(wèn)。

Retrofit2和OkHttp3實(shí)例化過(guò)程中使用到了建造者模式(不贅述涉及模式)。

  1. 完整的網(wǎng)絡(luò)訪問(wèn)設(shè)置:添加上攔截器(基于Java項(xiàng)目,開(kāi)發(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("訪問(wèn)失敗");
    }

    }

    interface ApiService {@GET("sug?code=utf-8&q=java&callback=cb")
    br/>@GET("sug?code=utf-8&q=java&callback=cb")
    }

到此Retrofit2講解完畢。語(yǔ)言組織的不好,有什么問(wèn)題大家可以留言,相互學(xué)習(xí)。

當(dāng)前標(biāo)題:Retrofit2的使用
當(dāng)前URL:http://chinadenli.net/article0/gidoio.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App開(kāi)發(fā)、網(wǎng)站改版、定制網(wǎng)站、用戶(hù)體驗(yàn)、企業(yè)網(wǎng)站制作、網(wǎng)站設(shè)計(jì)公司

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

綿陽(yáng)服務(wù)器托管