前言
网络请求框架基于Retrofit2构建,力求为开发者提供简洁、高效的函数调用接口,轻松地发送RESTful类型请求。
此框架采用建造者模式(Builder Pattern),具有完善的回调(Interface)。
程序代码在com.qilu.core.net包下。
1. 添加相关依赖
api 'com.squareup.okio:okio:1.14.0'
api 'com.squareup.okhttp3:okhttp:3.10.0'
api 'com.squareup.retrofit2:retrofit:2.4.0'
api 'com.squareup.retrofit2:converter-scalars:2.3.0'
2. public interface RestService
若要使用Retrofit2,必须依照官方文档构建一个接口(Interface),这个接口中包含App将使用的一切有关网络请求的方法。
所有方法的返回值类型为retrofit2.Call,一个由Retrofit2提供的回调。
package com.qilu.core.net;
import java.util.List;
import java.util.WeakHashMap;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.PartMap;
import retrofit2.http.QueryMap;
import retrofit2.http.Url;
public interface RestService {
@GET
Call<String> get(@Url String url, @QueryMap WeakHashMap<String, String> params);
@GET
Call<String> getWithToken(@Header("Authorization") String token, @Url String url,
@QueryMap WeakHashMap<String, String> params);
@GET
Call<String> getNoParams(@Url String url);
@GET
Call<String> getNoParamsWithToken(@Header("Authorization") String token, @Url String url);
@Multipart
@POST
Call<String> postRaw(@Url String url, @PartMap WeakHashMap<String, RequestBody> params);
@Multipart
@POST
Call<String> postRawWithToken(@Header("Authorization") String token, @Url String url,
@PartMap WeakHashMap<String, RequestBody> params);
@Multipart
@POST
Call<String> upload(@Url String url, @Part MultipartBody.Part file);
@Multipart
@POST
Call<String> uploadWithToken(@Header("Authorization") String token, @Url String url,
@Part MultipartBody.Part file);
@Multipart
@POST
Call<String> postWithFiles(@Url String url, @PartMap WeakHashMap<String, RequestBody> params,
@Part List<MultipartBody.Part> parts);
@Multipart
@POST
Call<String> postWithFilesWithToken(@Header("Authorization") String token,
@Url String url,
@PartMap WeakHashMap<String, RequestBody> params,
@Part List<MultipartBody.Part> parts);
}
3. public enum HttpMethod
创建枚举类型HttpMethod,方便判断RESTful请求类型
package com.qilu.core.net;
public enum HttpMethod {
GET,
GET_NO_PARAMS,
POST_RAW,
POST_WITH_FILES,
UPLOAD,
GET_WITH_TOKEN,
GET_NO_PARAMS_WITH_TOKEN,
POST_RAW_WITH_TOKEN,
POST_WITH_FILES_WITH_TOKEN,
UPLOAD_WITH_TOKEN,
}
4. public class RestCreator
RestCreator用于生成全局唯一的RESTful请求服务的实例,相关的配置信息包含超时时间、主机地址等。
package com.qilu.core.net;
import com.qilu.core.app.ConfigKeys;
import com.qilu.core.app.Qilu;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retr