public static String convertObjetc2XMl(Map<String, Object> map) {
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\" encoding=\"GBK\"?>");
sb.append("<MAPS>" + "<PUBLIC>");
sb.append("<TRXCODE>" + map.get("TRXCODE") + "</TRXCODE>");
sb.append("<APP_CODE>10056</APP_CODE>");
sb.append("<TRX_ORIGIN>01</TRX_ORIGIN>");
sb.append("</PUBLIC>");
sb.append("<PRIVATE>");
map.remove("TRXCODE");
//遍历Map对象,将key-value拼到报文中
for (Map.Entry<String, Object> entry : map.entrySet()) {
sb.append("<" + entry.getKey() + ">").append(entry.getValue()).append("</" + entry.getKey() + ">");
System.out.println(entry.getKey() + ":" + entry.getValue());
}
sb.append("</PRIVATE>" + "</MAPS>");
return sb.toString();
}
引入jar包:
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
</dependency>
//实现方法
public static Map<String, String> convertRoadRespXMLToMap(String respXML) {
Map<String, String> map = new HashMap<>();
String xml = dealXML(respXML);
Document document = null;
try {
document = DocumentHelper.parseText(xml);
Element rootElement = document.getRootElement();
Iterator iterator = rootElement.elementIterator();
while (iterator.hasNext()) {
//这里根据实际返回报文情况,结合实际决定是否需要再次添加遍历根节点的代码
Element element = (Element) iterator.next();
map.put(element.getName(), element.getTextTrim());
System.out.println(element.getName() + ":" + element.getTextTrim());
}
} catch (DocumentException e) {
logger.info("convertRoadRespXMLToMap返回报文转换成Map对象异常:"+e.getMessage());
}
return map;
}
// 将xml头部信息去掉
public static String dealXML(String xml) {
if (xml.lastIndexOf("?") != -1) {
xml = xml.substring(xml.lastIndexOf("?") + 2);
}
return xml;
}
/*
* url:请求地址
* port:请求端口号
* reqXML:请求报文
*/
public static String getRespXML(String url,int port,String reqXML) {
String result = null;
byte[] res =null;
Socket socket = null;
InputStream is = null;;
OutputStream os = null;
try {
socket = new Socket(url,port);
socket.setSoTimeout(10000);
is = socket.getInputStream();
os = socket.getOutputStream();
os.write(reqXML.getBytes("GBK"));//这里注意编码,是以什么编码类型发送过去
os.flush();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer =new byte[8192];
int count;
while((count = is.read(buffer)) != -1) {
bos.write(buffer,0,count);
}
res = bos.toByteArray();
}catch(Exception e) {
logger.error("socket请求异常...");
}finally {
try {
if(os != null) {
os.close();
}
if(is != null) {
is.close();
}
if(socket != null) {
socket.close();
}
}catch(Exception e) {
logger.error("输入输出流关闭异常...");
}
}
try {
result = new String(res,"GBK");
} catch (UnsupportedEncodingException e) {
logger.error("字符串编码转化异常...");
}
return result;
}