其实内部是封装了Okhttp和Gson解析
public class CourseFragmentAPI { public static void get(String userId, BaseCallBack<CourseFragmentResponseEntity> callBack){ CourseFragmentService service = BaseRetrofit.getInstance().create(CourseFragmentService.class); Call<CourseFragmentResponseEntity> call = service.getData(userId); call.enqueue(callBack); } }
public interface CourseFragmentService { @GET("courses/my_order_list") Call<CourseFragmentResponseEntity> getData(@Query("userId") String userId); }
public class BaseRetrofit { private Retrofit retrofit; private static BaseRetrofit instance; private BaseRetrofit() { retrofit = new Retrofit.Builder().client(BaseOkHttpClient.getInstance()).baseUrl(Config.SERVER_URL).addConverterFactory(GsonConverterFactory.create()).build(); } public static BaseRetrofit getInstance() { if (instance == null) { synchronized (BaseRetrofit.class) { if (instance == null) { instance = new BaseRetrofit(); } } } return instance; } public <T> T create(Class<T> service) { return retrofit.create(service); } }
public class BaseOkHttpClient { public static OkHttpClient getInstance() { OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder(); httpClientBuilder.addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); HttpUrl originalHttpUrl = originalRequest.url(); HttpUrl.Builder builder = originalHttpUrl.newBuilder(); EncodeParas(originalHttpUrl, builder); addCommonParas(builder); HttpUrl url = builder.build(); Request.Builder requestBuilder = originalRequest.newBuilder() .url(url) .method(originalRequest.method(), originalRequest.body()); Request request = requestBuilder.build(); LogHelp.d("lyg", "request: " + request.method() + " " + request.url()); Response response = chain.proceed(request); MediaType contentType = null; String bodyString = null; if (response.body() != null) { contentType = response.body().contentType(); bodyString = response.body().string(); } LogHelp.d("lyg", "response: " + response.code() + "\n" + bodyString); if (response.body() != null) {// 深坑!打印body后原ResponseBody会被清空,需要重新设置body ResponseBody body = ResponseBody.create(contentType, bodyString); return response.newBuilder().body(body).build(); } else { return response; } } }); return httpClientBuilder.build(); } /** * 加密请求参数。debug模式不加密 * * @param originalHttpUrl */ private static void EncodeParas(HttpUrl originalHttpUrl, HttpUrl.Builder builder) { if (Config.isEncode) { String paras = generateXXTEAEncodedParas(getOriginURLEncodedParas(originalHttpUrl), generateUserSignature()); String sign = generateAPPSignature(paras); clearAllParas(originalHttpUrl, builder); if (!TextUtils.isEmpty(paras)) { builder.addQueryParameter("paras", paras); } if (!TextUtils.isEmpty(sign)) { builder.addQueryParameter("sign", sign); } } } private static void addCommonParas(HttpUrl.Builder builder) { builder.addQueryParameter("appId", Constant.APPId) .addQueryParameter("ct", Constant.ClientType) .addQueryParameter("v", Constant.APIVersion) .addQueryParameter("ch", App.getAppChannel()) .addQueryParameter("cv", App.getAppVsersion()); LoginResponseEntity.Data data = UserData.getUser(); if (!Config.isEncode && null != data && !TextUtils.isEmpty(data.getXuehuToken()) && data.getUserId() > 0) { builder.addQueryParameter("xuehuToken", data.getXuehuToken()) .addQueryParameter("userId", "" + data.getUserId()); } } private static void clearAllParas(HttpUrl originalHttpUrl, HttpUrl.Builder builder) { Set<String> queryParameterNames = originalHttpUrl.queryParameterNames(); for (String name : queryParameterNames) { builder.removeAllQueryParameters(name); } } private static String getOriginURLEncodedParas(HttpUrl originalHttpUrl) { StringBuilder builder = new StringBuilder(); Set<String> queryParameterNames = originalHttpUrl.queryParameterNames(); for (String name : queryParameterNames) { if (!TextUtils.isEmpty(builder.toString())) { builder.append("&"); } builder.append(name + "=" + originalHttpUrl.queryParameter(name)); } return builder.toString(); } private static String generateUserSignature() { StringBuilder builder = new StringBuilder(); String userSignLowerCase = ""; //Hmac签名 String userSign = ""; //Hmac签名转大写,截取前32位 String timeStamp = String.valueOf(System.currentTimeMillis()); LoginResponseEntity.Data data = UserData.getUser(); if (null != data && !TextUtils.isEmpty(data.getXuehuToken()) && data.getUserId() > 0 && !TextUtils.isEmpty(data.getUserKey())) { int stringAsciiSum = StringHelp.stringAsciiSum(data.getUserKey() + timeStamp); String content = data.getXuehuToken() + timeStamp + Constant.APIVersion; userSignLowerCase = Hmac.getSignature(content, data.getUserKey(), Constant.SignatureType[stringAsciiSum % 5]); LogHelp.d("lyg", "type: " + stringAsciiSum % 5); } if (!TextUtils.isEmpty(userSignLowerCase)) { if (userSignLowerCase.length() > 32) { userSign = userSignLowerCase.substring(0, 32).toUpperCase(); } else { userSign = userSignLowerCase.toUpperCase(); } builder.append("xuehuToken=" + data.getXuehuToken()); builder.append("&userId=" + data.getUserId()); builder.append("×tamp=" + timeStamp); builder.append("&userSign=" + userSign); } return builder.toString(); } private static String generateXXTEAEncodedParas(String urlEncodedOriginParas, String userSignature) { String content = ""; if (!TextUtils.isEmpty(urlEncodedOriginParas)) { if (!TextUtils.isEmpty(userSignature)) { content = urlEncodedOriginParas + "&" + userSignature; } else { content = urlEncodedOriginParas; } } else if (!TextUtils.isEmpty(userSignature)) { content = userSignature; } if (!TextUtils.isEmpty(content)) { return XXTEA.encode(content, Constant.APPSecret).replace("\n", ""); } else { return content; } } private static String generateAPPSignature(String xxteaEncodedOriginParas) { //appId+clientType+format+version+paras String signContent = Constant.APPId + Constant.ClientType + Constant.APIFormat + Constant.APIVersion + xxteaEncodedOriginParas; String sign = Hmac.getSignature(signContent, Constant.SignSecret, Constant.SignatureType[1]); if (!TextUtils.isEmpty(sign)) { return sign.toUpperCase(); } return ""; } }