1添加依賴.
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
implementation 'com.squareup.retrofit2:retrofit:2.2.0'
implementation 'com.squareup.retrofit2:converter-gson:2.2.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.2.0'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.2.0'
2.RetrofitManager
public class RetrofitManager {
private static final String TAG = "RetrofitManager";
private static RetrofitManager mRetrofitManager;
private Retrofit mRetrofit;
private RequestServes apiService;
public static RetrofitManager getInstance() {
if (mRetrofitManager == null) {
synchronized (RetrofitManager.class) {
if (mRetrofitManager == null) {
mRetrofitManager = new RetrofitManager();
}
}
}
return mRetrofitManager;
}
private RetrofitManager() {
initRetrofit();
}
public void initRetrofit() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();//添加訪問網絡的日誌
logging.setLevel(HttpLoggingInterceptor.Level.BODY);//日誌級別
/*
**打印retrofit信息部分
*/
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
//打印retrofit日誌
Log.e("RetrofitLog", "retrofitBack = " + message);
}
});
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()//okhttp設置部分,此處還可再設置網絡參數
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
.addHeader("access_token", SharedPreferencesUtil.get(applicationContext, "token", "") + "")
.build();
return chain.proceed(request);
}
})
.addInterceptor(loggingInterceptor)
.build();
Log.e(TAG, "initRetrofit: ");
mRetrofit = new Retrofit.Builder()
.baseUrl(BaseUtil.HOST)
.client(client)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
Log.e(TAG, "initRetrofit: " + mRetrofit);
apiService = mRetrofit.create(RequestServes.class);
}
public RequestServes getService() {
Log.e(TAG, "getService: " + apiService);
return apiService;
}
public static RequestBody getBody(HashMap map) {
Gson gson = new Gson();
String strEntity = gson.toJson(map);
Log.e("=====json串", strEntity);
RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);
return body;
}}
3.RequestServes接口
public interface RequestServes {
@POST("communal/order")//post請求提交json
Call<CreateOrderBean> postPay(@Body RequestBody route);
@FormUrlEncoded
@POST("property/houseuserrelation/add")//post請求提交表單
Call<HttpResultBean<LoginResultBean>> addPayAddress(@Field("userId") String userId, @Field("houseId") String houseId);
@PUT("property/userCommunity/modifyUserCommunity")//put請求提交json
Call<String> putModify(@Body RequestBody route);
@DELETE("property/houseuserrelation/delete")//delete請求提交表單
Call<HttpResultBean<LoginResultBean>> deleteHouse(@Query("id") String id);
@GET("property/userCommunity/getUserCommunity/{userId}")//get請求直接拼"/"加參數
Call<HttpResultBean<CommunityChaBean>> getUserCommunity(@Path("userId") String userId);
@GET("property/house/selectBuildingById")//get請求
Call<HttpResultArrayBean<ChooseBuildingBean>> getHouse(@Query("id") String id);
}
4.HttpResultArrayBean
public class HttpResultArrayBean<T> {
private int statusCode;
@SerializedName(value = "message", alternate = "msg")
private String msg;
private List<T> items;
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public String getMsg() {
return msg == null ? "" : msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List<T> getItems() {
if (items == null) {
return new ArrayList<>();
}
return items;
}
public void setItems(List<T> items) {
this.items = items;
}
}
5.HttpResultBean
public class HttpResultBean<T> {
private int statusCode;
@SerializedName(value = "message", alternate = "msg")
private String msg;
private T items;
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public String getMsg() {
return msg == null ? "" : msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getItems() {
return items;
}
public void setItems(T items) {
this.items = items;
}
public HttpResultBean toResponse() {
HttpResultBean httpResultBean = new HttpResultBean();
httpResultBean.setStatusCode(statusCode);
httpResultBean.setMsg(msg);
return httpResultBean;
}
}
6.BaseUtil
public class BaseUtil {
public static final String HOST = "http://";}
7.應用
RetrofitManager.getInstance().getService().postPay(body).enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()) {
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
}
});
// //緩存路徑 // File cacheFile = new File(Environment.getExternalStorageDirectory(), "HttpCache"); // Cache cache = new Cache(cacheFile, 1024 * 1024 * 10);//緩存文件爲100MB // Log.e(TAG, "initRetrofit: " + cacheFile.getAbsolutePath()); // // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // // OkHttpClient httpClient = new OkHttpClient.Builder() // .addInterceptor(new Interceptor() { // @Override // public Response intercept(Chain chain) throws IOException { // Request request = chain.request() // .newBuilder() //// .addHeader("TSQ-RequestId", BaseUtil.encryptByPublicKey()) // .build(); // return chain.proceed(request); // } // }) // .connectTimeout(5, TimeUnit.SECONDS)//設置連接超時 // .readTimeout(10, TimeUnit.SECONDS)//讀取超時 // .writeTimeout(10, TimeUnit.SECONDS)//寫入超時 // .addInterceptor(interceptor)//添加日誌攔截器 //// .addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)//添加緩存攔截器 // .cache(cache)//把緩存添加進來 // .build();