shz.third.AbstractThirdApiRequest Maven / Gradle / Ivy
package shz.third;
import shz.*;
import java.io.InputStream;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("unchecked")
public abstract class AbstractThirdApiRequest implements ThirdApiRequest {
private static final long serialVersionUID = -8925162828875377223L;
protected final Class tCls;
protected AbstractThirdApiRequest() {
tCls = (Class) AccessibleHelp.getParameterizedType(getClass(), AbstractThirdApiRequest.class, "T");
}
protected abstract void info(String msg);
@Override
public T execute(D data) {
init(data);
String url = url();
String body = body();
info(Help.format("请求接口,url:%s,body:%s", url, body));
Charset charset = charset();
try {
String response = read(HttpHelp.requestIs(
url, this::sslContext, headers(), method(), body == null ? null : body.getBytes(charset),
proxyHost(), proxyPort(), connectTimeout(), readTimeout()
), charset);
info(Help.format("接口响应,url:%s,response:%s", url, response));
return analysis(response);
} catch (Exception e) {
throw PRException.of(e);
}
}
protected String read(InputStream is, Charset charset) {
StringWriter sw = new StringWriter();
IOHelp.read(IOHelp.getBr(is, charset), sw);
return sw.toString();
}
protected abstract T analysis(String response);
protected List fields() {
return AccessibleHelp.fields(getClass(), f -> (f.getModifiers() & Modifier.STATIC) == 0 && !ignoreField(f.getName()));
}
protected boolean ignoreField(String fieldName) {
return "tCls".equals(fieldName);
}
protected Map dataMap() {
List fields = fields();
if (fields.isEmpty()) return Collections.emptyMap();
Map dataMap = new HashMap<>();
for (Field field : fields)
try {
String name = field.getName();
Object obj = field.get(this);
String key = nameFilter(name, obj);
if (key == null) continue;
String value = valueFilter(name, obj);
if (value == null) continue;
dataMap.put(key, value);
} catch (IllegalAccessException ignored) {
}
return dataMap.isEmpty() ? Collections.emptyMap() : dataMap;
}
protected String nameFilter(String name, Object value) {
return name;
}
protected String valueFilter(String name, Object value) {
return value == null ? null : value.toString();
}
protected final String jointUrl(String url) {
return HttpHelp.jointUrl(url, dataMap());
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy