import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.http.HttpStatus;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;
public class wishPostUtil {
/**
* 读写wishpost传参xml
*WishPostCreateOrderParam 〈创建wishPost订单需要的参数类〉
* @param param
*/
public static Document setXmlParam(WishPostCreateOrderParam param) {
SAXReader reader = new SAXReader();
Document doc;
String info ="";
try {
doc = reader.read(new FileInputStream(wishPostUtil.class.getClassLoader().getResource("wishpost.xml").getFile()),"UTF-8");
Element root = doc.getRootElement();
Node access_token_node = root.selectSingleNode("access_token");
Node bid_node = root.selectSingleNode("bid");
String bid = String.valueOf(Integer.parseInt(bid_node.getText()) + 1);
List<Element> cleanElement = root.elements("order");
for(Element e:cleanElement){
root.remove(e);
}
for (WishOrders oders : param.getOrder()) {
Element order = root.addElement("order");
for (Field field : oders.getClass().getDeclaredFields()) {
Object value = getFieldValueByName(field.getName(), oders);
if (value != null) {
order.addElement(field.getName()).setText(value.toString());
}
}
}
access_token_node.setText(param.getAccess_token());
bid_node.setText(bid);
try {
saveDocument(doc, new FileOutputStream(wishPostUtil.class.getClassLoader().getResource("wishpost.xml").getFile()));
String strXml = transXmlToString(new File(wishPostUtil.class.getClassLoader().getResource("wishpost.xml").getFile()));
String url = "https://wishpost.wish.com/api/v2/create_order";
info = returnInfo(url,strXml);
return strPraseToXml(info);
} catch (IOException e) {
e.printStackTrace();
}
} catch (DocumentException e) {
e.printStackTrace();
}catch (FileNotFoundException e){
e.printStackTrace();
}finally {
return strPraseToXml(info);
}
}
/**
* 根据属性名获取属性值
*
* @param fieldName
* @param o
* @return
*/
private static Object getFieldValueByName(String fieldName, Object o) {
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = o.getClass().getMethod(getter, new Class[]{});
Object value = method.invoke(o, new Object[]{});
return value;
} catch (Exception e) {
return null;
}
}
// 下面的为固定代码---------可以完成java对XML的写,改等操作
public static void saveDocument(Document document, FileOutputStream xmlFile) throws IOException {
Writer osWrite = new OutputStreamWriter(xmlFile);// 创建输出流
OutputFormat format = OutputFormat.createPrettyPrint(); // 获取输出的指定格式
format.setEncoding("GBK");// 设置编码 ,确保解析的xml为UTF-8格式
XMLWriter writer = new XMLWriter(osWrite, format);// XMLWriter
// 指定输出文件以及格式
writer.write(document);// 把document写入xmlFile指定的文件(可以为被解析的文件或者新创建的文件)
writer.flush();
writer.close();
}
/**
* 将xml转换成String
* @param file
* @return
*/
public static String transXmlToString(File file){
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = null;
StringWriter writer = new StringWriter();
try {
dBuilder = dbFactory.newDocumentBuilder();
org.w3c.dom.Document doc = dBuilder.parse(file);
DOMSource domSource = new DOMSource(doc);
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
// 将转换过的xml的String 样式打印到控制台
System.out.println(writer.toString());
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}finally {
return writer.toString();
}
}
public static String returnInfo(String url,String strXml){
HttpClient httpclient = new HttpClient();
PostMethod post = new PostMethod(url);
String info = null;
try {
RequestEntity entity = new StringRequestEntity(strXml, "application/xml",
"utf-8");
post.setRequestEntity(entity);
httpclient.executeMethod(post);
int code = post.getStatusCode();
if (code == HttpStatus.SC_OK)
info = new String(post.getResponseBodyAsString()); //接口返回的信息
} catch (Exception ex) {
ex.printStackTrace();
} finally {
post.releaseConnection();
return info;
}
}
public static Document strPraseToXml(String xmlStr){
Document document = null;
try {
document = DocumentHelper.parseText(xmlStr);
} catch (DocumentException e) {
e.printStackTrace();
}finally {
return document;
}
}
}