最近在开发微信代扣,涉及大量HTTP调用微信,就写了一个泛型模板,将序列化,反序列化,HTTP调用全部整合至泛型基类中.
public abstract class WxCallbackHandler<C extends WeixinReturnParameter> implements CallbackHandler {
private static final org.slf4j.Logger LOG= LoggerFactory.getLogger(WxCallbackHandler.class);
private static final String XML_TAG="xml";
protected ThreadLocal<C> context=new ThreadLocal<C>();
private static final Charset UTF8_CHARSET=Charset.forName("utf-8");
private XStream xStream;
private static XStream wxCommonResultXStream;
static {
wxCommonResultXStream = NoNameCoderWithCDataFacotry.Instance().create();
wxCommonResultXStream.autodetectAnnotations(Boolean.TRUE);
wxCommonResultXStream.alias(XML_TAG,WeixinXmlResult.class);
}
public WxCallbackHandler(){
xStream = NoNameCoderWithCDataFacotry.Instance().create();
xStream.autodetectAnnotations(Boolean.TRUE);
//-----------------------------------------------------------------以下为获取泛型参数-----------------------------
Class current=this.getClass();
while(!WxCallbackHandler.class.equals(current.getSuperclass())){
current=current.getSuperclass();/*为了处理多级继承*/
}
Type genType = current.getGenericSuperclass();
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
//=============================================获取泛型参数结束=======================
xStream.alias(XML_TAG, (Class) params[0]);
}
private void parser(CallbackParameter parameter){
ServletInputStream inputStream=null;
try {
inputStream=parameter.getRequest().getInputStream();
String xmlText = IOUtils.toString(inputStream, UTF8_CHARSET);
if (LOG.isInfoEnabled()) {
LOG.info("微信回调请求报文如下{}{}", parameter.toString(), xmlText);
}
context.set((C) xStream.fromXML(xmlText));
}catch (Throwable throwable){
LOG.error(throwable.getMessage(),throwable);
throw new RuntimeException(throwable);
}finally {
IOUtils.closeQuietly(inputStream);
}
}
@Override
public void execute(CallbackParameter parameter) {
parser(parameter);
WeixinXmlResult result=new WeixinXmlResult(doExecute());
if(LOG.isInfoEnabled()){
LOG.info("回复微信调用结果如下{}", GsonUtils.defaultGson().toJson(result));
}
PrintWriter writer=null;
try {
HttpServletResponse response = parameter.getResponse();
writer = response.getWriter();
writer.print(wxCommonResultXStream.toXML(result));
writer.flush();
}catch (Throwable throwable){
LOG.error(throwable.getMessage(),throwable);
throw new RuntimeException(throwable);
}
finally {
IOUtils.closeQuietly(writer);
}
}
public abstract boolean doExecute();
}