使用场景:
客户端需要将实体数据同步到平台库,这里采用的是HTTP的形式,以下用户数据同步到平台库为例
1.需要导入xstream.jar
2.定义请求和响应的父类实体数据,方便后续编码
/**
* 请求响应的父类对象
*/
public class Generic
{
public Header header;
}
3.定义消息头实体,用于存放请求的操作类型编码和响应类型状态码
/**
* 定义请求和响应头实体属性
*/
public class Header
{
/** 数据操作类型编码 */
public String reqCode;
/** 数据响应类型编码 */
public String respCode;
}
4.定义用户数据请求对象,这里需要使用到xstream的注解
/**
* 请求实体对象定义
*/
@XStreamAlias("Request")
public class ReqUser extends Generic
{
/** 定义具体是请求数据 */
public ReqDataByUser data;
}
6.定义用户数据响应对象,这里需要使用到xstream的注解
/**
* 响应实体对象定义
*/
@XStreamAlias("Response")
public class RespUser extends Generic
{
/** 定义具体是响应数据 */
public RespDataByUser data;
}
7.创建将实体对象转换为请求或响应的xml文件
public static <T extends Generic> String packReqObject(T reqObj){
XStream stream = new XStream(new DomDriver("utf-8"));
stream.processAnnotations(reqObj.getClass());
String xml = stream.toXML(reqObj);
xml = XMLDECLARE + xml;
return xml;
}
8.创建将请求或响应的xml文件转换为实体对象
public static <T extends Generic> T unpackReqObject(String reqXml, Class<T> clazz){
XStream stream = new XStream(new DomDriver("utf-8"));
stream.processAnnotations(clazz);
return (T) stream.fromXML(reqXml);
}
9.创建请求前的数据组装
public void send() throws Exception{
ReqUser reqUser = new ReqUser();
reqUser.header = new Header();
reqUser.header.reqCode = "1001";
reqUser.data = new ReqDataByUser();
String xml = MsgUtil.packReqObject(reqUser);
String responseStr = CommonService.postData("http://127.0.0.1:8080/user", xml);
RespUser respUser = MsgUtil.unpackReqObject(responseStr, RespUser.class);
}
10.创建发送请求和接收响应消息类
public static String postData(String url, String str) throws Exception{
URL myUrl = new URL(url);
HttpURLConnection con = (HttpURLConnection)myUrl.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setUseCaches(false);
con.setInstanceFollowRedirects(true);
con.setRequestProperty("Content-Type", "text/plain");
con.setRequestProperty("charset", "utf-8");
con.connect();
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.flush();
out.close();
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try{
br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String aLine = null;
while((aLine = br.readLine()) != null){
sb.append(aLine);
}
}catch(Exception e){
}finally{
br.close();
}
con.disconnect();
return sb.toString();
}
以上代码主要功能为客户端像服务端发送数据请求的功能
下列为服务端处理客户端发送请求的代码
1.将请求的流转换为xml字符串
/**
* 将请求流中的数据转换为字符串
*/
public static String converRequestData(InputStream in) throws Exception{
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try{
br = new BufferedReader(new InputStreamReader(in));
String aLine = null;
while((aLine = br.readLine()) != null){
sb.append(aLine);
}
}catch(Exception e){
}finally{
br.close();
}
return sb.toString();
}
2.根据请求的消息头Header中定义的reqCode,映射对应的实体对象
private static Map<String, String> getStubMap(){
Map<String, String> stubMap = new HashMap<String, String>();
stubMap.put("1001", "org.pojo.user.request.ReqDataByUser");
return stubMap;
}
3.根据传入的属性查找xml文件节点的值
private String getNodeValue(String xml, String aTag){
String ret = "";
int startIndex = xml.indexOf("<" + aTag.trim() + ">");
int endIndex = xml.indexOf("</" + aTag.trim() + ">");
if((startIndex >= 0) && (endIndex >= 0) && (startIndex + aTag.length() + 2 < endIndex)){
ret = xml.substring(startIndex + aTag.length() + 2, endIndex).trim();
}
return ret;
}
String reqXml = converRequestData(request.getInputStream());
// 获取Head
String headerValue = getNodeValue(reqXml, "Head");
// 获取请求的类型编码
String reqCode = getNodeValue(headerValue, "reqCode");
Class clazz = null;
// 判断当前的类型编码如果在Map中则实例化他,并返回
if(getStubMap().containsKey(reqCode)){
String classPath = getStubMap().get(reqCode);
clazz = Class.forName(classPath);
}
// 将请求的xml文件转换为对应的实体对象
Generic generic = MsgUtil.unpackReqObject(reqXml, clazz);
//....... 这里写具体的代码处理,将generic对象传入
// 请求完成后响应数据处理
response.setContentType("text/plain");
response.setCharacterEncoding("utf-8");
// 将结果通过打包发送到客户端
String respXml = MsgUtil.packReqObject(generic);
byte[] sendBytes = respXml.getBytes("utf-8");
response.getWriter().println(new String(sendBytes));
response.getWriter().flush();
response.getWriter().close();