【框架】网络请求+Gson解析--Retrofit 2

时间:2021-08-21 10:00:50

其实内部是封装了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("&timestamp=" + 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 "";
}
}

【框架】网络请求+Gson解析--Retrofit 2的更多相关文章

  1. 网络请求&plus;Gson解析--Retrofit 2

    其实内部是封装了Okhttp和Gson解析 public class CourseFragmentAPI { public static void get(String userId, BaseCal ...

  2. 怎样使用ListView实现一个带有网络请求,解析,分页,缓存的公共的List页面来大大的提高工作效率

    在寻常的开发中常常会有非常多列表页面.每做一个列表页就须要创建这个布局文件那个Adapter适配器文件等等一大堆与之相关的附属的不必要的冗余文件. 假设版本号更新迭代比較频繁,如此以往,就会使项目pr ...

  3. Android网络请求与解析

    1.Volley和Gson结合使用——Volley适用于小型数据,多次的请求,使用Gson解析时,服务器数据的键值不能包含常用的标识符如:class.....等,这些就需要与服务端小伙伴商量 这样也可 ...

  4. Android Http请求框架二:xUtils 框架网络请求

    一:对Http不了解的请看 Android Http请求框架一:Get 和 Post 请求 二.正文 1.xUtils 下载地址 github 下载地址  : https://github.com/w ...

  5. IOS SWIFT 网络请求JSON解析 基础一

    前言:移动互联网时代,网络通信已经是手机端必不可少的功能.应用中也必不可少地使用了网络通信,增强客户端与服务器交互.使用NSURLConnection实现HTTP的通信.NSURLConnection ...

  6. Android检查设备是否可以访问互联网,判断Internet连接,测试网络请求,解析域名

    安卓SDK提供了ConnectivityManager类,那么我们就可以轻松的获取设备的网络状态以及联网方式等信息. 但是要想知道安卓设备连接的网络能不能访问到Internet,就要费一番周折了. 本 ...

  7. Win&lpar;Phone&rpar;10开发第&lpar;3&rpar;弹,简单的Demo程序网络请求json解析列表显示

    先分享一个由Json字符串直接生成解析对应的类的工具: jsonclassgenerator14 百度天气接口 下面是由一个小功能(又特么的是天气)的实现,记录下下UAP的流程和结构(其实跟之前一模一 ...

  8. java HttpClicent网络请求与解析

    HttpClicent是Apache下的一个子项目,文档齐全,详见官网:http://hc.apache.org/httpcomponents-client-4.5.x/quickstart.html ...

  9. Android okHttp网络请求之Retrofit&plus;Okhttp&plus;RxJava组合

    前言: 通过上面的学习,我们不难发现单纯使用okHttp来作为网络库还是多多少少有那么一点点不太方便,而且还需自己来管理接口,对于接口的使用的是哪种请求方式也不能一目了然,出于这个目的接下来学习一下R ...

随机推荐

  1. tidyr包--数据处理包

    tidyr包的作者是Hadley Wickham.这个包常跟dplyr结合使用.本文将介绍tidyr包中下述四个函数的用法: gather—宽数据转为长数据.类似于reshape2包中的melt函数 ...

  2. Laravel Predis Error while reading line from the server&period;

    问题 Laravel说明文档中的 Redis 发布与订阅案例,命令行运行php artisan redis:subscribe 到60s自动断开并报错 [Predis\Connection\Conne ...

  3. Watir、Selenium2、QTP区别

    1.支持的语言 Watir:ruby Selenium2:支持多种语言,如:python,ruby,java,c#,php,perl,javascript QTP:vbscript 2.支持的浏览器 ...

  4. 通过gdb调试分析Linux内核的启动过程

    作者:吴乐 山东师范大学 <Linux内核分析>MOOC课程http://mooc.study.163.com/course/USTC-1000029000 一.实验流程 1.打开环境 执 ...

  5. &lbrack;Form builder&rsqb;&colon;about SYSTEM&period;MESSAGE&lowbar;LEVEL

    If you want to suppress error messages then you have to set a system variable :system.message_level. ...

  6. 客户端技术:Cookie 服务端技术:HttpSession

    客户端技术:Cookie 服务端技术:HttpSession 07. 五 / android基础 / 没有评论   一.会话技术1.什么是会话:客户打开浏览器访问一个网站,访问完毕之后,关闭浏览器.这 ...

  7. Ubuntu14&period;04: Error found when loading &sol;root&sol;&period;profile

    问题描述: 启用root账号登录后系统出现如下提示信息: Error found when loading /root/.profile stdin:is not a tty 解决方法: 在终端中用命 ...

  8. React&period;createClass和extends Component的区别

    React.createClass和extends Component的区别主要在于: 语法区别 propType 和 getDefaultProps 状态的区别 this区别 Mixins 语法区别 ...

  9. &lbrack;Cassandra&rsqb; Mutation of &lt&semi;x&gt&semi; bytes is too large for the maxiumum size of &lt&semi;y&gt&semi;

    [Cassandra] Mutation of bytes is too large for the maxiumum size of Q: WARN [SharedPool-Worker-4] 20 ...

  10. 字符集更改步骤,mysql乱码

    关键字:Mysql乱码,mysql字符集修改 #字符集更改步骤~