現(xiàn)在Android網(wǎng)絡(luò)請求大部分已經(jīng)換成了Retrofit2.0 +RxJava + 0kHttp3.0俭驮,Retrofit 使用接口的方式葛家,負責(zé)請求的數(shù)據(jù)和請求的結(jié)果名挥,OkHttp 負責(zé)請求的過程狼钮,RxJava 負責(zé)異步,各種線程之間的切換真朗。毫無疑問這三劍客 已成為當前Android 網(wǎng)絡(luò)請求最流行的方式此疹。
簡介
Retrofit: Retrofit是Square 公司開發(fā)的一款基于restful風(fēng)格接口的Android 網(wǎng)絡(luò)請求的框架,對Okhttp做了一層封裝遮婶。網(wǎng)絡(luò)請求還是基于Okhttp蝗碎,我們只需要通過簡單的配置就能使用Retrofit來進行網(wǎng)絡(luò)請求了。Retrofit官網(wǎng)
RxJava:RxJava 在 GitHub 主頁上介紹 "a library for composing asynchronous and event-based programs using observable sequences for the Java VM"(一個在 Java VM 上使用可觀測的序列來組成異步的旗扑、基于事件的程序的庫)蹦骑。總之臀防,rxjava讓異步操作變得非常簡單眠菇。RxJava
OkHttp: Square 公司開源的網(wǎng)絡(luò)請求庫。 OkHttp
基本使用
HTTP協(xié)議中共定義了八種方法或者叫“動作”來表明對Request-URI指定的資源的不同操作方式袱衷,分別是OPTIONS捎废、HEAD、GET致燥、POST登疗、PUT、DELETE、TRACE辐益、CONNECT断傲,介紹就省略了。
雖然有這么多種請求方式智政,但App的接口請求無非就是數(shù)據(jù)的增刪改查认罩,增刪改查對應(yīng)到Restful風(fēng)格接口上也就是post,delete续捂,put垦垂,get四種請求。在Retrofit框架提供的注解中疾忍,其中HTTP注解有五個乔外,用來修飾請求方法床三,除了post一罩,delete,put撇簿,get還有一個head聂渊。除了這五種網(wǎng)絡(luò)請求方式外,App無非還會用到retrofit的單文件或者多文件的上傳下載四瘫,同步請求或者異步請求的處理汉嗽,還有okhttp數(shù)據(jù)緩存的問題。
注解 | 請求方式 | 用途 |
---|---|---|
@Path | GET | 用于替換Url路徑中的變量字符 |
@Query | GET | 用于拼接在Url路徑后的查詢參數(shù)找蜜,但相對于直接在Url后拼接饼暑,@Query則是添加一個變量 |
@QueryMap | GET | 效果等同于多個@Query 參數(shù)為Map類型 |
@FormUrlEncoded/@Field | POST | @FormUrlEncoded修飾表單域,每個表單域子件key-value采用@Field修飾 |
@Body | POST | 可以指定一個對象作為HTTP請求體@Body |
@FormUrlEncoded/@Field | PUT | @FormUrlEncoded修飾表單域洗做,每個表單域子件key-value采用@Field修飾 |
@HTTP/@Body | DELETE | @HTTP修飾表單域弓叛,以指定一個對象作為HTTP請求體@Body,此時表單域一定要寫上hasBody = true |
@Multipart/@Part或者@PartMap | POST | 文件上傳使用诚纸,@Multipart修飾表單域撰筷,參數(shù)@Part修飾或者參數(shù)使用@PartMap |
舉例說明
引入依賴
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'io.reactivex:rxjava:1.1.9'
compile 'io.reactivex:rxandroid:1.2.1'
創(chuàng)建Retrofit對象
public class RetrofitManager {
private static RetrofitManager mRetrofitManager;
private Retrofit mRetrofit;
private RetrofitManager(){
initRetrofit();
}
public static synchronized RetrofitManager getInstance(){
if (mRetrofitManager == null){
mRetrofitManager = new RetrofitManager();
}
return mRetrofitManager;
}
private void initRetrofit() {
HttpLoggingInterceptor LoginInterceptor = new HttpLoggingInterceptor();
LoginInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(new RspCheckInterceptor());
if (AppConfig.DEBUG){
builder.addInterceptor(LoginInterceptor);
}
builder.connectTimeout(15, TimeUnit.SECONDS);
builder.readTimeout(20, TimeUnit.SECONDS);
builder.writeTimeout(20, TimeUnit.SECONDS);
builder.retryOnConnectionFailure(true);
OkHttpClient client = builder.build();
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
.setExclusionStrategies(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return false;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
})
.create();
mRetrofit = new Retrofit.Builder()
.baseUrl(AppConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(client)
.build();
}
public <T> T createReq(Class<T> reqServer){
return mRetrofit.create(reqServer);
}
}
創(chuàng)建訪問API的請求
/**
* 添加標簽
*
* @param supplier_id
* @param staff_id
* @param name
* @param type
* @return
*/
@FormUrlEncoded
@POST("memberservice/addMemberTag/suppliers/{supplier_id}/operator/{staff_id}")
Observable<BaseResponse> addMemberTag(@Path("supplier_id") String supplier_id,
@Path("staff_id") String staff_id,
@Field("name") String name, @Field("type") String type, @Field("timestamp") String timestamp);
/**
* 刪除標簽(注意一定要寫hasBody = true,否則delete不能使用body參數(shù)請求)
*
* @param supplier_id
* @param operator_id
* @return
*/
@HTTP(method = "DELETE", path = "memberservice/delMemberTag/suppliers/{supplier_id}/operator/{operator_id}", hasBody = true)
Observable<BaseResponse> deletMemberTag(@Path("supplier_id") String supplier_id,
@Path("operator_id") String operator_id,
@Body RequestBody content);
/**
* 修改標簽
*
* @param supplier_id
* @param operator_id
* @param map
* @return
*/
@FormUrlEncoded
@PUT("memberservice/updateMemberTag/suppliers/{supplier_id}/operator/{operator_id}")
Observable<BaseResponse> updateMemberTag(@Path("supplier_id") String supplier_id,
@Path("operator_id") String operator_id,
@FieldMap Map<String, String> map);
/**
* 查詢標簽
*
* @param supplier_id
* @param staff_id
* @return
*/
@GET("memberservice/queryStaffTag/suppliers/{supplier_id}/operator/{staff_id}")
Observable<BaseResponse<TagsBean>> queryMemberTag(@Path("supplier_id") String supplier_id,
@Path("staff_id") String staff_id,
@Query("timestamp") String timestamp);
}
發(fā)送請求以及處理結(jié)果
RetrofitManager.getInstance().createReq(Api.class).addMemberTag(supply_id, staff_id, data, "2", getTime()).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Subscriber<BaseResponse>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
//處理請求失敗的操作
}
@Override
public void onNext(BaseResponse baseResponse) {
//處理成功后的結(jié)果
}
});
多圖以及單圖上傳
方法一:
@Multipart
@POST("suppliers/{supplier_id}/staff/{staff_id}/meeting/{meeting_id}/upload")
Observable<BaseResponse> uploadePics(
@Path("supplier_id")String supplier_id,@Path("staff_id")String staff_id,
@Path("meeting_id")String meeting_id,@Part List<MultipartBody.Part> partList);
MultipartBody.Builder builder = new MultipartBody.Builder()
.setType(MultipartBody.FORM)//表單類型
.addFormDataPart("summary_position", formatted_address); //地理位置
//單張或者多張
for (int i = 0; i < listString.size(); i++) {
File file = new File(listString.get(i));
RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
builder.addFormDataPart("summary_pics[]", file.getName(), imageBody);
}
List<MultipartBody.Part> parts = builder.build().parts();
RetrofitManager2.getInstance().createReq(PhpApi.class).uploadePics(
supplier_id,staff_id,meeting_id,parts)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Subscriber<BaseResponse>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(BaseResponse baseResponse) {
}
});
方法二:
Observable<BaseResponse> uploadePics2(
@Path("supplier_id")String supplier_id,@Path("staff_id")String staff_id,
@Path("meeting_id")String meeting_id,
@PartMap Map<String, RequestBody> params);
//單張或多張圖片
List<File>files = new ArrayList<File>();
for (int i = 0; i < listString.size(); i++) {
File file = new File(listString.get(i));
files.add(file);
}
//組裝partMap對象
Map<String, RequestBody> partMap = new HashMap<>();
for(File file : files ){
RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), file);
partMap.put("summary_pics[]\"; filename=\""+file.getName()+"\"", fileBody);
}
RequestBody formatted_addressString = RequestBody.create(MediaType.parse("text/plain"), formatted_address);
partMap.put("summary_position" , formatted_addressString);
RetrofitManager2.getInstance().createReq(PhpApi.class).uploadePics2(
supplier_id,staff_id,meeting_id,partMap)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Subscriber<BaseResponse>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(BaseResponse baseResponse) {
}
});