首先是依赖库
//网络请求
implementation 'com.squareup.retrofit2:retrofit:2.6.1'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.squareup.okhttp3:okhttp:3.12.1'
retrofit2 是okhttp3封装 gson 解释json格式的字符串。 `
//返回Retrofit对象
public Retrofit getMyRetrofit(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseUrl)
//可以接收自定义的Gson
//Retrofit会使用Gson将ResponseBody
.client(okHtpClient)
.addConverterFactory(MyGsonConverterFactory.create())
.build();
return retrofit;
}
okhttp的拦截器话 看个人喜欢, 上依赖库 `
//日志的拦截器
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'
implementation 'com.squareup.okhttp3:mockwebserver:3.9.1'
//Facebook强大的监测工具
implementation 'com.facebook.stetho:stetho-okhttp3:1.3.1'
拦截器
import android.util.Log;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
/**
* 类描述:
* 创建人:
* 时间: 2021/1/1411:40
*/
class OkHttpLogger {
private static final String TAG = "OkHttpLogger";
private static final long DEFAULT_READ_TIMEOUT_MILLIS = 15 * 1000;
private static final long DEFAULT_WRITE_TIMEOUT_MILLIS = 20 * 1000;
private static final long DEFAULT_CONNECT_TIMEOUT_MILLIS = 20 * 1000;
private static final long HTTP_RESPONSE_DISK_CACHE_MAX_SIZE = 10 * 1024 * 1024;
private static volatile OkHttpLogger instance;
private OkHttpClient okHttpClient;
private Boolean ISYES;
private String code="x";
private OkHttpLogger() {
ISYES = false;
HttpLoggingInterceptor interceptor =
new HttpLoggingInterceptor(message -> {
synchronized (instance) {
Log.i(TAG, message);
}
});
//包含header、body数据
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// setlevel用来设置日志打印的级别,共包括了四个级别:NONE,BASIC,HEADER,BODY
// BASEIC:请求/响应行
// HEADER:请求/响应行 + 头
// BODY:请求/响应行 + 头 + 体
okHttpClient = new OkHttpClient.Builder()
.readTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
.writeTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
.connectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
//FaceBook 网络调试器,可在Chrome调试网络请求,查看SharePreferences,数据库等
.addNetworkInterceptor(new StethoInterceptor())
.addInterceptor(interceptor).build();
}
public static OkHttpLogger getInstance() {
if (instance == null) {
synchronized (OkHttpLogger.class) {
if (instance == null) {
instance = new OkHttpLogger();
}
}
}
return instance;
}
/**
* 获取OkHttpClient
*
* @return
*/
public OkHttpClient getOkHttpClient() {
return okHttpClient;
}
}
Callback的封装
import android.view.View;
import com.example.wakuang.data.BaseData;
import com.google.android.material.snackbar.Snackbar;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public abstract class MyCallback<T> implements Callback<BaseData<T>> {
private View view;
public MyCallback(View view) {
this.view=view;
}
@Override
public void onResponse(Call<BaseData<T>> call, Response<BaseData<T>> response) {
if(response.body()!=null){
if(response.body().getCode()==200){
succeed(response);
}else{
Snackbar.make(view, response.body().getMessage(), Snackbar.LENGTH_LONG).show();
}
}else {
Snackbar.make(view, response.message(), Snackbar.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<BaseData<T>> call, Throwable t) {
Snackbar.make(view, t.getMessage(), Snackbar.LENGTH_LONG).show();
}
public abstract void succeed(Response<BaseData<T>> response);
}
样例
//获取验证码
@GET("sso/getAuthCode")
Call<BaseData<String>> myVerifyCode(@Query("telephone") String telephone);
public class BaseData<T> {
private int code;
private String message;
private T data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public String toString() {
return "BaseData{" +
"code=" + code +
", message='" + message + ''' +
", data=" + data +
'}';
}
}
private void authaCode() {
Call<BaseData<String>> codeCall = MyApp.getMyAPP().getHttpNetaddress().myVerifyCode(binding.phone.getText().toString());
codeCall.enqueue(new MyCallback<String>(binding.getRoot()) {
@Override
public void succeed(Response<BaseData<String>> response) {
CountDownTimerUtils mCountDownTimerUtils = new CountDownTimerUtils(binding.authaCode, 60000, 1000);
mCountDownTimerUtils.start();
new MessageDialog(response.body().getMessage()).show(getChildFragmentManager(), MessageDialog.class.getName());
}
});
}
建议不要过度封装,保持高扩展性。 混淆时候,记得放开解析json对象,会空指针