HttpClient提交XML格式数据

来源:互联网 发布:房屋室外设计软件 编辑:程序博客网 时间:2024/06/05 18:45

package com.skywin.simpass.sysinterface.sms.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.skywin.simpass.sysinterface.sms.entity.SMSEntity;

public class SMSAuth {

    // 获得ConnectionManager,设置相关参数
    private static MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager();
    private static int connectionTimeOut = 180000;
    private static int socketTimeOut = 120000;
    private static int maxConnectionPerHost = 5;
    private static int maxTotalConnections = 100;

    // 标志初始化是否完成的flag
    private static boolean initialed = false;

    // LOG4j
    static Logger logger = Logger.getLogger(SMSAuth.class);

    // 初始化ConnectionManger的方法
    private static void SetPara() {
        manager.getParams().setConnectionTimeout(connectionTimeOut);
        manager.getParams().setSoTimeout(socketTimeOut);
        manager.getParams().setDefaultMaxConnectionsPerHost(
                maxConnectionPerHost);
        manager.getParams().setMaxTotalConnections(maxTotalConnections);
        initialed = true;
    }

    /**
     * 对响应结果的处理
     *
     * @param telephone
     */
    public SMSEntity smsAuthResult(String telephone) {
        // int result = -1;
        // String msg = null;

        Map<String, String> m = smsAuthResponse(telephone);
        // result = Integer.parseInt(m.get("RetCode"));
        // System.out.println("返回码:"+m.get("RetCode"));    //返回代码
        // System.out.println("SIMPASS卡号:"+m.get("Value")); //SIMPASS卡号
        SMSEntity entity = new SMSEntity();
        entity.setRetCode(m.get("RetCode"));
        entity.setSimpassNo(m.get("Value"));
        entity.setTelephone(telephone);
        return entity;
    }

    /**
     * 获取响应结果
     *
     * @param telephone
     * @return
     */
    private Map<String, String> smsAuthResponse(String telephone) {
        HttpClient client = new HttpClient(manager);
        //本机代理和端口
        client.getHostConfiguration().setProxy("your proxy", proxy_port);
        //验证地址和端口
        client.getHostConfiguration().setHost("destination_url_ip", port, "http");
        if (initialed != true) {
            SMSAuth.SetPara();
        }
        // 使用POST方式提交数据
        HttpMethod postMethod = getPostMethod(telephone);
        InputStream is = null;
        try {
            logger.debug("正在进行认证!!!!!!!!!!!!!!!");
            client.executeMethod(postMethod);
            if (postMethod.getStatusCode() != HttpStatus.SC_OK) {
                logger.error("Method failed: " + postMethod.getStatusLine());
                return null;
            }
            logger.debug("开始解析数据!!!!!!!!!!!!!!!");
            is = postMethod.getResponseBodyAsStream();
            SAXReader sr = new SAXReader();
            Document document = sr.read(is);
            // 获取根元素
            Element element = document.getRootElement();
            logger.info("认证平台返回的xml:/r" + element.asXML());
            return parseHttpClientData(element);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("进行认证异常时间TIME************"
                    + new Timestamp(System.currentTimeMillis()));
            return null;
        } finally {
            // 资源的释放
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
            if (postMethod != null) {
                postMethod.releaseConnection();
            }
        }

    }

    /**
     * 使用POST方式提交数据
     *
     * @return
     *
     */
    private static HttpMethod getPostMethod(String telephone){
        PostMethod post = new PostMethod(
                "/CA-bizcontrol/bizcontrol/Auth.action");

        //POST XML数据
        String requestContent = "<?xml version=/"1.0/" encoding=/"UTF-8/"?>"
                + "<AuthReq>"
                + "<BPID>110002</BPID>"
                + "<BSID>1100020003</BSID>"
                + "<Type>201</Type>"
                + "<User>" + telephone + "</User>"
                + "<Content></Content>"
                + "<Sign></Sign>"
                + "</AuthReq>";
       
        System.out.println(requestContent);

        //网上的以文件形式POST的方式
        /*
         * File input = new File("D://01//simpass//auth.xml"); try {
         * post.setRequestBody(new FileInputStream(input)); if (input.length() <
         * Integer.MAX_VALUE) post.setRequestContentLength(input.length()); else
         * post.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED);
         *  // 指定请求内容的类型 post.setRequestHeader("Content-type", "text/xml;
         * charset=UTF-8"); } catch (FileNotFoundException e) { // TODO
         * Auto-generated catch block e.printStackTrace(); }
         */
       
        //使用StringRequestEntity POST XML
        try {
            post
                    .setRequestEntity(new StringRequestEntity(requestContent, "text/xml",
                            "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return post;
    }

    /*
     * 解析认证返回数据
     */
    private static Map<String, String> parseHttpClientData(Element root) {
        Hashtable resMap = new Hashtable();
        if (root.getName().equals("AuthResp")) {
            /*
             * resMap.put("AuthResp", element.getName()); resMap.put("RetCode",
             * element.elementText("RetCode"));
             */
            // 获取根元素下的第一个RetCode元素
            Element element = root.element("RetCode");
            resMap.put("RetCode", element.getText());
            // 获得RetResult元素
            Element retResult = root.element("RetResult");

            // 显示RetResult元素的所有子元素
            // displayAllSubElement(retResult);
            List<Element> childs = retResult.elements();
            resMap.put("Type", childs.get(0).getText());
            resMap.put("Value", childs.get(1).getText());
            return resMap;
        } else {
            System.err.println("没有返回结果");
            return null;
        }
    }

    public static void main(String[] args) {
        SMSEntity entity = new SMSAuth().smsAuthResult("13922201109");
        System.out.println("认证平台返回码:" + entity.getRetCode());
    }
}

原创粉丝点击