記錄一下Retrofit

1.先添加依賴

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

compile 'com.squareup.retrofit2:converter-gson:2.3.0'

//引入Log攔截器,方便DEBUG模式輸出log信息

? ? compile 'com.squareup.okhttp3:logging-interceptor:3.5.0'

? ? compile 'com.github.franmontiel:PersistentCookieJar:v1.0.1'


2.創(chuàng)建一個接口類(比如下圖)


3.新建application類

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();

? ? ? ? loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

? ? ? ? Gson gson = new GsonBuilder()

? ? ? ? ? ? ? ? .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")

? ? ? ? ? ? ? ? .create();//使用 gson coverter,統(tǒng)一日期請求格式

? ? ? ? OkHttpClient okHttpClient = new OkHttpClient.Builder()

? ? ? ? ? ? ? ? .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)

? ? ? ? ? ? ? ? .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)

? ? ? ? ? ? ? ? .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)

? ? ? ? ? ? ? ? .addInterceptor(loggingInterceptor)

? ? ? ? ? ? ? ? .cookieJar(new PersistentCookieJar(new SetCookieCache(),new SharedPrefsCookiePersistor(this)))

? ? ? ? ? ? ? ? .build();

? ? ? ? Retrofit retrofit = new Retrofit.Builder()

? ? ? ? ? ? ? ? .baseUrl(Constant.BASE_URL)

? ? ? ? ? ? ? ? .addConverterFactory(GsonConverterFactory.create(gson))

? ? ? ? ? ? ? ? .client(okHttpClient)

? ? ? ? ? ? ? ? .build();

? ? ? HttpApi mApi = retrofit.create(HttpApi.class);

(mApi抽取成靜態(tài)成員變量,方便直接調(diào)用)

4.Get請求如圖1

? ? Post請求如下圖(分帶參和無參)


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容