使用前準(zhǔn)備
Build.gradle文件配置
- dependencies配置
compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
網(wǎng)絡(luò)框架搭建
- 服務(wù)創(chuàng)建類封裝(HTTP):
public class ServiceGenerator {
public static final String API_BASE_URL = "";
public static int READ_TIMEOUT = 60;
public static int WRIT_TIMEOUT = 60;
public static int CONNECT_TIMEOUT = 60;
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
.readTimeout(READ_TIMEOUT,TimeUnit.SECONDS)//設(shè)置讀取超時(shí)時(shí)間
.writeTimeout(WRIT_TIMEOUT,TimeUnit.SECONDS)//設(shè)置寫的超時(shí)時(shí)間
.connectTimeout(CONNECT_TIMEOUT,TimeUnit.SECONDS);
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL) .addConverterFactory(GsonConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
return createService(serviceClass, null);
}
public static <S> S createService(Class<S> serviceClass, final String authToken) {
if (authToken != null) {
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
}
OkHttpClient client = httpClient
// 日志攔截器
.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.build();
Retrofit retrofit = builder.client(client).build();
return retrofit.create(serviceClass);
}
}
使用說(shuō)明:
API_BASE_URL 用來(lái)配置api主地址
READ_TIMEOUT 用來(lái)配置讀取超時(shí)時(shí)間
WRIT_TIMEOUT 用來(lái)配置寫超時(shí)時(shí)間
CONNECT_TIMEOUT 用來(lái)配置連接超時(shí)時(shí)間
addConverterFactory() 用來(lái)設(shè)置解析器,此處我們?cè)O(shè)置的是gson的解析
addInterceptor() 用來(lái)設(shè)置日志攔截器
- 服務(wù)創(chuàng)建類封裝(HTTPS):
public class HttpsServiceGenerator {
public static final String API_BASE_URL = "";
public static int READ_TIMEOUT = 250;
public static int WRIT_TIMEOUT = 250;
public static int CONNECT_TIMEOUT = 250;
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL) .addConverterFactory(GsonConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
return createService(serviceClass, null);
}
public static <S> S createService(Class<S> serviceClass, final String authToken) {
if (authToken != null) {
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
}
Retrofit retrofit = builder.client(getUnsafeOkHttpClient()).build();
return retrofit.create(serviceClass);
}
private static OkHttpClient getUnsafeOkHttpClient() {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
X509Certificate[] x509Certificates = new X509Certificate[0];
return x509Certificates;
}
}
};
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient okHttpClient =
new OkHttpClient.Builder()
.readTimeout(READ_TIMEOUT,TimeUnit.SECONDS)//設(shè)置讀取超時(shí)時(shí)間
.writeTimeout(WRIT_TIMEOUT,TimeUnit.SECONDS)//設(shè)置寫的超時(shí)時(shí)間
.connectTimeout(CONNECT_TIMEOUT,TimeUnit.SECONDS)
.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.sslSocketFactory(sslSocketFactory)
.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}).build();
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
使用說(shuō)明:
可以看出https 和http的服務(wù)類主要區(qū)別在于retrofit對(duì)象的構(gòu)造方法不同哈踱。
主要就是sslSocketFactory()方法蚓哩。是用來(lái)添加sslsocketFactory的者祖,也就是客戶端發(fā)送的請(qǐng)求都等于手持了這樣的證書(shū),這樣就可以和服務(wù)器交互了悦施。
SslsocketFactory對(duì)象的獲取方法如下:
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
- 請(qǐng)求體和響應(yīng)體封裝:
{
"page":2,
"pageSize":10
}
Json體類似如上所示的可以封裝為如下的請(qǐng)求體/響應(yīng)體,此處可以借用GsonFormat插件,輸入json體就可以快速生產(chǎn)請(qǐng)求體/響應(yīng)體bean類郭赐。
public class GetTradeDetailRequest {
/**
* page : 2
* pageSize : 10
*/
private int page;
private int pageSize;
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
}
- 服務(wù)接口封裝:
public interface BalanceService {
@GET("balance")
Call<GetBalanceResponse> getBalance(@Header("AccessToken") String accessToken);
@POST("balance/detail")
Call<GetTradeDetailResponse> getDetail(@Header("AccessToken") String accessToken , @Body GetTradeDetailRequest tradeDetailRequest);
}
使用說(shuō)明:
此接口用來(lái)聲明請(qǐng)求類型,call聲明的類型是返回體的bean類,@header是請(qǐng)求的頭确沸,@body是返回體的類型捌锭。
- 請(qǐng)求model封裝:
public class BalanceModel {
private static BalanceModel balanceModel;
private BalanceService mBalanceService;
/**
* Singleton
*/
public static BalanceModel getInstance(Context context) {
if (balanceModel == null) {
balanceModel = new BalanceModel(context);
}
return balanceModel;
}
public BalanceModel(Context context) {
mBalanceService = HttpsServiceGenerator.createService(BalanceService.class);
}
public Call<GetBalanceResponse> getBalanceResponseCall(String accessToken) {
Call<GetBalanceResponse> balanceResponseCall = mBalanceService.getBalance(accessToken);
return balanceResponseCall;
}
}
使用說(shuō)明:
此接口用來(lái)聲明請(qǐng)求model的俘陷,主要用到的是上面的服務(wù)接口。 此類主要用來(lái)獲取網(wǎng)絡(luò)請(qǐng)求體的观谦。
- 響應(yīng)事件回調(diào)類封裝:
public abstract class Callback<T extends Object> implements retrofit2.Callback<T> {
@Override
public void onResponse(Call<T> call, Response<T> response) {
if (response.raw().code() == 200){
Log.i("internet response","200");
onSuccess(response);
}else if (response.raw().code() == 404){
Log.i("internet response","404");
onNotFound();
}
}
@Override
public void onFailure(Call<T> call, Throwable t) {
}
public abstract void onSuccess(Response<T> response);
public void onNotFound(){
return;
}
}
使用說(shuō)明:
通常在發(fā)送網(wǎng)絡(luò)請(qǐng)求的時(shí)候只有兩種結(jié)果拉盾,一是請(qǐng)求發(fā)送失敗,二是服務(wù)器接收到了請(qǐng)求并且響應(yīng)了豁状。
onFailure()主要用來(lái)處理請(qǐng)求發(fā)送失敗的情況捉偏,onResponse()用來(lái)處理服務(wù)器的響應(yīng)內(nèi)容。
response.raw().code()的值就是我們?cè)诰W(wǎng)站開(kāi)發(fā)中遇到的標(biāo)識(shí)代碼泻红,200代表成功返回消息體夭禽,404代表api路徑?jīng)]找到(api路徑配置出錯(cuò)是會(huì)導(dǎo)致這樣的情況,當(dāng)然也可能是服務(wù)器的環(huán)境出了問(wèn)題承桥,導(dǎo)致手機(jī)訪問(wèn)不到)驻粟,500代表的是服務(wù)器內(nèi)部錯(cuò)誤(請(qǐng)求中的參數(shù)配置有誤會(huì)導(dǎo)致這樣的情況)。
- 代碼中使用:
private void httpLoginRequest(String phone, String password) {
mPushToken = mPushAgent.getRegistrationId();
GetLoginRequest loginRequest = new GetLoginRequest();
loginRequest.setPhone(phone);
loginRequest.setPassword(password);
loginRequest.setPushtoken(mPushToken);
loginRequest.setCarrier(mCarrier);
final Call<GetLoginResponse> callLogin = loginModel.getLoginResponseCall(loginRequest);
callLogin.enqueue(new Callback<GetLoginResponse>() {
@Override
public void onFailure(Call<GetLoginResponse> calllist, Throwable t) {
ToastUtils.showToast(LoginActivity.this,"網(wǎng)絡(luò)服務(wù)異常");
materialDialog.dismiss();
callLogin.cancel();
}
@Override
public void onSuccess(Response<GetLoginResponse> response) {
GetLoginResponse loginResponse = response.body();
userBean = loginResponse.getData();
if (loginResponse.getErrcode() == 0) {
ToastUtils.showToast(LoginActivity.this,"登錄成功");
ActivityCollector.finishAll();
startActivity(new Intent(LoginActivity.this, MapActivity.class));
AppConfigUtils.getInstanse(LoginActivity.this).clearAll();
AppConfigUtils.getInstanse(LoginActivity.this).setUserBean(userBean);
materialDialog.dismiss();
} else if (loginResponse.getErrcode() == 203) {
ToastUtils.showToast(LoginActivity.this,"用戶名或密碼錯(cuò)誤");
materialDialog.dismiss();
}else if (loginResponse.getErrcode() == 999){
materialDialog.dismiss();
ToastUtils.showToast(LoginActivity.this,"服務(wù)器異常凶异,請(qǐng)稍后再試");
}
callLogin.cancel();
}
@Override
public void onNotFound() {
materialDialog.dismiss();
ToastUtils.showToast(LoginActivity.this,"404");
super.onNotFound();
callLogin.cancel();
}
});
}
private void httpBalanceRequest(String accessToken) {
BalanceModel balanceModel = BalanceModel.getInstance(getApplicationContext());
final Call<GetBalanceResponse> balanceResponseCall = balanceModel.getBalanceResponseCall(accessToken);
balanceResponseCall.enqueue(new Callback<GetBalanceResponse>() {
@Override
public void onResponse(Call<GetBalanceResponse> calllist, Response<GetBalanceResponse> response) {
GetBalanceResponse balanceResponse = response.body();
if (balanceResponse.getErrcode() == 0) {
mMoneyTV.setText(balanceResponse.getData().getBalance());
} else if (balanceResponse.getErrcode() == 999) {
ToastUtils.showToast(BalanceActivity.this,"服務(wù)器異常蜀撑,請(qǐng)稍后再試");
mMoneyTV.setText("0.00");
} else if (balanceResponse.getErrcode() == 403) {
ToastUtils.showToast(BalanceActivity.this,"登錄已失效,請(qǐng)重新登錄");
AppConfigUtils.getInstanse(BalanceActivity.this).clearAll();
ActivityCollector.finishAll();
LoginActivity.actionStart(BalanceActivity.this,mPhone,"");
}
balanceResponseCall.cancel();
}
@Override
public void onFailure(Call<GetBalanceResponse> calllist, Throwable t) {
ToastUtils.showToast(BalanceActivity.this,"網(wǎng)絡(luò)服務(wù)異常");
balanceResponseCall.cancel();
}
});
}
使用說(shuō)明:
這段代碼使用的是自己封裝的響應(yīng)事件回調(diào)類剩彬,當(dāng)然也可以用第二張圖retrofit默認(rèn)的那套酷麦,用自己封裝的有個(gè)好處就是404not found 可以處理進(jìn)行操作,如果用默認(rèn)的那套喉恋,在404的時(shí)候這段代碼就會(huì)崩潰沃饶。