import org.dom4j.Document; //导入方法依赖的package包/类
/**
* 保存http请求信息到xml
*
* @param hc
* @return
* @throws Exception
*/
public static boolean saveHttpConfig(HttpConfig hc) throws Exception {
SAXReader reader = new SAXReader();
File xml = new File(HTTP_CONFIG_FILE);
Document doc = null;
Element root = null;
boolean isNew = true;
if (!xml.exists()) {
doc = DocumentHelper.createDocument();
root = DocumentHelper.createElement("root");
root.addElement("configs");
doc.add(root);
}
if (doc == null) {
try (FileInputStream in = new FileInputStream(xml); Reader read = new InputStreamReader(in, "UTF-8")) {
doc = reader.read(read);
root = doc.getRootElement();
}
}
Element cfg = (Element) root.selectSingleNode("/root/configs");
Element e = (Element) root.selectSingleNode("/root/configs/config[@name='" + hc.getName() + "']");
if (e != null) {
isNew = false;
cfg.remove(e);
}
CONFIG_MAP.put(hc.getName(), hc);
Element cfg1 = cfg.addElement("config");
cfg1.addAttribute("name", hc.getName());
cfg1.addAttribute("encodeType", hc.getEncodeType());
cfg1.addAttribute("charset", hc.getCharset());
cfg1.addAttribute("requestType", hc.getRequestType());
cfg1.addAttribute("sendXML", hc.getSendXML().toString());
cfg1.addAttribute("packHead", hc.getPackHead().toString());
cfg1.addAttribute("lowercaseEncode", hc.getLowercaseEncode().toString());
cfg1.addElement("url").setText(hc.getUrl());
cfg1.addElement("header").setText(hc.getHeaderStr());
cfg1.addElement("parameter").setText(hc.getParameterStr());
cfg1.addElement("encodeField").setText(hc.getEncodeFieldName());
cfg1.addElement("encodeKey").setText(hc.getEncodeKey());
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(new FileOutputStream(xml), format);
writer.write(doc);
writer.close();
return isNew;
}