面试中有一个题目是发送(接受)xml,并解析。
当时有接触但是没有注意,所以回来强力关注下,并且记录在这,大家一起学习下:
1:将Java对象转换成xml格式String
项目中的常用的手段是使用freemarker
/**
*
*/
package ora.object2xml;
import java.io.IOException;
import java.io.StringWriter;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
* @author lenovo
*
*/
public class MessageTempleteManager
{
private static MessageTempleteManager tplm = null;
private Configuration cfg = null;
private MessageTempleteManager()
{
cfg = new Configuration();
try
{
cfg.setClassForTemplateLoading(this.getClass(), "/ora/object2xml/templete/");
}
catch (Exception e)
{
}
}
private static Template getTemplate(String name) throws IOException
{
if(tplm == null)
{
tplm = new MessageTempleteManager();
}
return tplm.cfg.getTemplate(name);
}
public static String process(String templatefile, Object param) throws IOException, TemplateException
{
Template template=MessageTempleteManager.getTemplate(templatefile);
StringWriter sw = new StringWriter();
template.process(param, sw);
return sw.toString();
}
}
test类
/**
*
*/
package ora.object2xml;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.TemplateException;
/**
* @author lenovo
*
*/
public class Test
{
public static void main(String[] args) throws IOException, TemplateException
{
Map<String,Object> param = new HashMap<String, Object>();
param.put("path","111111");
System.out.println(MessageTempleteManager.process("test.ftl", param));
}
}
ftl文件:
<?xml version="1.0" encoding="UTF-8"?>
<Root our="${path}" state="0" />
测试结果如下:
<?xml version="1.0" encoding="UTF-8"?>
<Root our="111111" state="0" />
2:将xml格式的String发送
public static StringBuffer sendSoapMsg(String soapMessage,
String targetUrl, String soapAction, Long timeout) throws Exception
{
busLogger.enterFuncDebugLog(soapMessage, soapAction, targetUrl, timeout);
//保存响应消息
HttpURLConnection conn = null;
BufferedReader bf = null;
StringBuffer sb = new StringBuffer();
try
{
URL url = new URL(targetUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.addRequestProperty("SOAPAction", soapAction);
conn.addRequestProperty("Content-type", "text/xml; charset=UTF-8");
//默认超时时间30秒
conn.setConnectTimeout(timeout.intValue());
//将发送请求参数写入到http请求中
conn.getOutputStream().write(soapMessage.getBytes());
conn.getOutputStream().flush();
conn.getOutputStream().close();
//从服务器获取响应结果
InputStream in = conn.getInputStream();
//从服务器读取结果
bf = new BufferedReader(new InputStreamReader(in));
String s = null;
while ((s = bf.readLine()) != null)
{
sb.append(s);
}
}
catch (Exception e)
{
busLogger.excepFuncDebugLog(e);
throw e;
}
finally
{
if (null != bf)
{
try
{
bf.close();
}
catch (IOException e)
{
busLogger.excepFuncDebugLog(e);
}
}
if (conn != null)
{
conn.disconnect();
}
}
busLogger.exitFuncDebugLog(sb.toString());
return sb;
}
。其中的String内容为xml格式的。