public class Http2Bean<T> {
private final OkHttpClient client = new OkHttpClient();
private final Class<T> clazz;
private final Request.Builder request;
private String url = "";
private String method = "GET";
private Activity activity;
/**
* 初始化扫描传入的bean类,获取其Url注解上的附带信息
* @param clazz 指定数据对应的bean
*/
public Http2Bean(Class<T> clazz) {
this.clazz = clazz;
Url info = this.clazz.getAnnotation(Url.class);
this.method = info.method();
this.url = GlobalSetting.baseUrl + info.url();
this.request = new Request.Builder().addHeader("Authorization", "").url(this.url);
}
/**
* 执行请求
*
* @param param 请求参数,根据bean类附加信息,判断这次请求是什么方法,如果是get/delete方法则将参数拼接
* 在请求地址后面。如果是post/put方法则将参数转为JSON作为请求体发送。
* @param callback 回调函数,用于请求到数据后使用这个数据执行一些动作。
*/
public void execute(Object param, final H2BCallBack<T> callback) {
RequestBody requestBody = null;
if (param != null && !this.method.equals("GET") && !this.method.equals("DELETE")) {
requestBody = RequestBody.create(new Gson().toJson(param), MediaType.parse("application/json;charset=UTF-8"));
} else {
this.request.url(this.url + "/" + param.toString());
}
RequestBody finalRequestBody = requestBody;
Thread thread = new Thread(() -> {
String result = null;
try {
result = this.client
.newCall(this.request.method(method, finalRequestBody).build())
.execute()
.body()
.string()
.replace("null", "\"0\"")
.replace("\\{\\}", "\"0\"");
} catch (IOException e) {
e.printStackTrace();
}
String finalResult = result;
activity.runOnUiThread(() -> {
T bean = new Gson().fromJson(finalResult, clazz);
callback.invoke(bean);
});
});
thread.start();
}
public Http2Bean<T> bind(Activity activity) {
this.activity = activity;
return this;
}
/**
* 函数式接口,用作回调函数
*
* @param <T>
*/
interface H2BCallBack<T> {
/**
* 唯一方法,满足函数式接口条件
* @param bean 传入响应数据,在方法中进行得到数据后的操作。
*/
void invoke(T bean);
}
/**
* 注解,用于附加在bean类上,标记该bean类对应的请求地址以及请求方法
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Url {
String url();
String method() default "GET";
}
}
标签:String,url,param,method,bean,OkHttp,Http2Bean,clazz,Gson
From: https://www.cnblogs.com/maplerain/p/16908411.html