背景
android開發(fā)過程中網(wǎng)絡(luò)請求作為最重要的組成部分之一,然而對于大部分android開發(fā)者在網(wǎng)絡(luò)請求上有太多疑惑,不知道如何去選型?通過原生的HttpClient、HttpUrlConnection封裝?還是通過第三方框架再封裝?筆者以為采用廣泛被使用的第三方網(wǎng)絡(luò)框架再封裝為上策,因為這些網(wǎng)絡(luò)框架如retrofit贩猎、okhttp熊户、volley等是被全球android開發(fā)者維護(hù)著,無論在功能上、性能上吭服、還是代碼簡潔性都相對于自己通過原生實(shí)現(xiàn)的給力.
目的
致力封裝一個簡潔嚷堡、實(shí)用、易移植的網(wǎng)絡(luò)框架模塊.
正題
今天筆者就給大家基于retrofit + okhttp + gson 封裝一個通用易懂的網(wǎng)絡(luò)框架模塊.
首先我們需要在gradle文件中將第三方依賴引入項目,代碼如下:
dependencies {
// retrofit + okhttp + gson
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
}
接著開始我們的封裝之路......
首先我們需要寫一個參數(shù)常量類,用于定義一些常量,如請求Url地址艇棕、接口返回信息,代碼如下:
/**
* @className: InterfaceParameters
* @classDescription: 參數(shù)配置
* @author: leibing
* @createTime: 2016/8/30
*/
public class InterfaceParameters {
// 請求URL
public final static String REQUEST_HTTP_URL = BuildConfig.API_URL;
// 接口返回結(jié)果名稱
public final static String INFO = "info";
// 接口返回錯誤碼
public final static String ERROR_CODE = "errorcode";
// 接口返回錯誤信息
public final static String ERROR_MSG = "errormsg";
}
然后寫一個網(wǎng)絡(luò)請求封裝類JkApiRequest.class,采用單例的方式,配置網(wǎng)絡(luò)請求參數(shù)以及返回網(wǎng)絡(luò)請求api實(shí)例,代碼如下:
/**
* @className:JkApiRequest
* @classDescription:網(wǎng)絡(luò)請求
* @author: leibing
* @createTime: 2016/8/30
*/
public class JkApiRequest {
// sington
private static JkApiRequest instance;
// Retrofit object
private Retrofit retrofit;
/**
* Constructor
* @author leibing
* @createTime 2016/08/30
* @lastModify 2016/08/30
* @param
* @return
*/
private JkApiRequest(){
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new OkHttpInterceptor())
.build();
retrofit = new Retrofit.Builder()
.baseUrl(InterfaceParameters.REQUEST_HTTP_URL)
.addConverterFactory(JkApiConvertFactory.create())
.client(client)
.build();
}
/**
* sington
* @author leibing
* @createTime 2016/08/30
* @lastModify 2016/08/30
* @param
* @return
*/
public static JkApiRequest getInstance(){
if (instance == null){
instance = new JkApiRequest();
}
return instance;
}
/**
* create api instance
* @author leibing
* @createTime 2016/08/30
* @lastModify 2016/08/30
* @param service api class
* @return
*/
public T create(Class service) {
return retrofit.create(service);
}
}
上面代碼有兩個網(wǎng)絡(luò)請求參數(shù)需要注意, OkHttpInterceptor 蝌戒、JkApiConvertFactory.
OkHttpInterceptor 作為網(wǎng)絡(luò)請求攔截器,可以攔截請求的數(shù)據(jù)以及響應(yīng)的數(shù)據(jù),有助于我們排查問題,而JkApiConvertFactory 是作為Convert工廠,這里我所做的就是解析返回來的數(shù)據(jù),將數(shù)據(jù)進(jìn)行Gson處理就是在這里面.
OkHttpInterceptor代碼如下:
/**
* @className: OkHttpInterceptor
* @classDescription: Http攔截器
* @author: leibing
* @createTime: 2016/08/30
*/
public class OkHttpInterceptor implements Interceptor {
private static final Charset UTF8 = Charset.forName("UTF-8");
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// 獲得Connection,內(nèi)部有route沼琉、socket北苟、handshake、protocol方法
Connection connection = chain.connection();
// 如果Connection為null打瘪,返回HTTP_1_1友鼻,否則返回connection.protocol()
Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
// 比如: --> POST http://121.40.227.8:8088/api http/1.1
String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol;
System.out.println("ddddddddddddddddddd requestStartMessage = " + requestStartMessage);
// 打印 Response
Response response;
try {
response = chain.proceed(request);
} catch (Exception e) {
throw e;
}
ResponseBody responseBody = response.body();
long contentLength = responseBody.contentLength();
if (bodyEncoded(response.headers())) {
} else {
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.buffer();
Charset charset = UTF8;
if (contentLength != 0) {
// 獲取Response的body的字符串 并打印
System.out.println("ddddddddddddddddddddddddd response = " + buffer.clone().readString(charset));
}
}
return response;
}
private boolean bodyEncoded(Headers headers) {
String contentEncoding = headers.get("Content-Encoding");
return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
}
}
JkApiConvertFactory代碼如下:
/**
* @className: JkApiConvertFactory
* @classDescription: this converter decode the response.
* @author: leibing
* @createTime: 2016/8/30
*/
public class JkApiConvertFactory extends Converter.Factory{
public static JkApiConvertFactory create() {
return create(new Gson());
}
public static JkApiConvertFactory create(Gson gson) {
return new JkApiConvertFactory(gson);
}
private JkApiConvertFactory(Gson gson) {
if (gson == null) throw new NullPointerException("gson == null");
}
@Override
public Converter responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
return new GsonResponseBodyConverter<>(type);
}
final class GsonResponseBodyConverter implements Converter {
private final Type type;
GsonResponseBodyConverter(Type type) {
this.type = type;
}
@Override public T convert(ResponseBody value) throws IOException {
BaseResponse baseResponse;
String reString;
try {
reString = value.string();
// 解析Json數(shù)據(jù)返回TransData對象
TransData transData = TransUtil.getResponse(reString);
try {
if (transData.getErrorcode().equals("0") && !TextUtils.isEmpty(transData.getInfo())) {
baseResponse = new Gson().fromJson(transData.getInfo(), type);
baseResponse.setSuccess(transData.getErrorcode().equals("0"));
baseResponse.setInfo(transData.getInfo());
baseResponse.setInfo(transData.getInfo());
} else {
baseResponse = (BaseResponse) StringUtil.getObject(((Class) type).getName());
baseResponse.setSuccess(transData.getErrorcode().equals("0"));
baseResponse.setInfo(transData.getInfo());
baseResponse.setInfo(transData.getInfo());
}
return (T)baseResponse;
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
//從不返回一個空的Response.
baseResponse = (BaseResponse) StringUtil.getObject(((Class) type).getName());
try {
baseResponse.setSuccess(false);
//JkApiConvertFactory can not recognize the response!
baseResponse.setErrormsg("");
} catch (Exception e) {
e.printStackTrace();
} finally {
return (T)baseResponse;
}
}
}
}
接著我們寫api接口,我這里是將對應(yīng)的接口封裝到對應(yīng)的類中,這樣當(dāng)前api類中接口名稱可以統(tǒng)一起來,請求api的方法也寫入當(dāng)前api類,這樣做既能解耦又能減少在使用處的冗余代碼,代碼如下:
/**
* @className: ApiLogin
* @classDescription: 登陸api
* @author: leibing
* @createTime: 2016/8/12
*/
public class ApiLogin {
// api
private ApiStore mApiStore;
/**
* Constructor
* @author leibing
* @createTime 2016/08/30
* @lastModify 2016/08/30
* @param
* @return
*/
public ApiLogin() {
// 初始化api
mApiStore = JkApiRequest.getInstance().create(ApiStore.class);
}
/**
* 登錄
* @author leibing
* @createTime 2016/08/30
* @lastModify 2016/08/30
* @param username 用戶名
* @param password 密碼
* @param callback 回調(diào)
* @return
*/
public void Login(String username, String password, ApiCallback callback){
Call mCall = mApiStore.login(URLEncoder.encode(username), password);
mCall.enqueue(new JkApiCallback(callback));
}
/**
* @interfaceName: ApiStore
* @interfaceDescription: 登錄模塊api接口
* @author: leibing
* @createTime: 2016/08/30
*/
private interface ApiStore {
@GET("app/User/Login")
Call login(
@Query("username") String username,
@Query("userpass") String userpass);
}
}
從上面代碼我們看到ApiCallback和JkApiCallback兩個回調(diào)接口,這兩者區(qū)別在哪呢?觀察仔細(xì)的童鞋會發(fā)現(xiàn)這個問題.ApiCallback接口是作為通用接口,而JkApiCallback是作為一個接口封裝類,針對不同數(shù)據(jù)情景,做不同回調(diào).
ApiCallback代碼如下:
/**
* @className: ApiCallback
* @classDescription: Api回調(diào)
* @author: leibing
* @createTime: 2016/08/30
*/
public interface ApiCallback {
// 請求數(shù)據(jù)成功
void onSuccess(T response);
// 請求數(shù)據(jù)錯誤
void onError(String err_msg);
// 網(wǎng)絡(luò)請求失敗
void onFailure();
}
JkApiCallback代碼如下:
public class JkApiCallback implements Callback {
// 回調(diào)
private ApiCallback mCallback;
/**
* Constructor
* @author leibing
* @createTime 2016/08/30
* @lastModify 2016/08/30
* @param mCallback 回調(diào)
* @return
*/
public JkApiCallback(ApiCallback mCallback){
this.mCallback = mCallback;
}
@Override
public void onResponse(Call call, Response response) {
if (mCallback == null){
throw new NullPointerException("mCallback == null");
}
if (response != null && response.body() != null){
if (((BaseResponse)response.body()).isSuccess()){
mCallback.onSuccess((T)response.body());
}else {
mCallback.onError(((BaseResponse) response.body()).getErrormsg());
}
}else {
mCallback.onFailure();
}
}
@Override
public void onFailure(Call call, Throwable t) {
if (mCallback == null){
throw new NullPointerException("mCallback == null");
}
mCallback.onFailure();
}
}
接下來我們寫Response類,用于接收Gson解析回來的數(shù)據(jù),這個只需寫json數(shù)據(jù)信息里面的字段.代碼如下:
/**
* @className: LoginResponse
* @classDescription: 獲取登錄返回的信息
* @author: leibing
* @createTime: 2016/08/30
*/
public class LoginResponse extends BaseResponse implements Serializable{
// 序列化UID 用于反序列化
private static final long serialVersionUID = 4863726647304575308L;
// token
public String accesstoken;
}
閱讀仔細(xì)的童鞋會發(fā)現(xiàn),在Convert工廠中Gson解析時,用到了一個BaseResponse,這個響應(yīng)類是作為基類,就是服務(wù)端返回的固定json數(shù)據(jù)格式,因為每個項目返回的固定格式可能不一樣,所以只需改這里,就能定制對應(yīng)項目的網(wǎng)絡(luò)框架.
BaseResponse代碼如下:
/**
* @className: BaseResponse
* @classDescription: 網(wǎng)絡(luò)請求返回對象公共抽象類
* @author: leibing
* @createTime: 2016/08/30
*/
public class BaseResponse implements Serializable {
// 序列化UID 用于反序列化
private static final long serialVersionUID = 234513596098152098L;
// 是否成功
private boolean isSuccess;
// 數(shù)據(jù)
public String info;
// 錯誤消息
public String errormsg;
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean success) {
isSuccess = success;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getErrormsg() {
return errormsg;
}
public void setErrormsg(String errormsg) {
this.errormsg = errormsg;
}
}
一個簡潔、實(shí)用瑟慈、易移植的網(wǎng)絡(luò)框架模塊封裝完畢.