读写xml、使用xml文件进行参数传递并获取返回内容——wishPost请求物流单号为例


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;
    }
}

}

​

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值