码迷,mamicode.com
首页 > 编程语言 > 详细

快递鸟电子面单打印功能基于java

时间:2018-11-02 23:36:13      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:进入   contex   sel   extend   注意   ipaddress   readonly   data   .data   

之前的后天管理系统的电子面单打印使用的是灵通打单。

使用相对比较麻烦,需要到处Excel之后再导入,麻烦。

快递鸟有电子面单api,后台系统直接对接很是方便,不过也遇到了好些问题。

不难是不难,但是遇到的坑着实是不少,特此记录一下。

快递鸟电子面单API地址:http://www.kdniao.com/api-eorder

都是在正式环境下,申请对应的商户id等一系列东西。

在对应的快递鸟后台,可以进行如下的批量打印。

技术分享图片

想把这个打印功能集成到自己内部系统,可以下载官方的demo

跑起来挺容易的,直接放入tomcat运行就可以了

不过demo需要tomcat8.5,需要修改的话找到项目的.settings文件夹下有一个

org.eclipse.wst.common.project.facet.core.xml 将tomcat8.5修改为对应的版本就可以了。

官方demo代码

 

package cc.kdniao.api;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.xml.internal.messaging.saaj.util.Base64;

/**
 * Servlet implementation class printOrder
 */
@WebServlet("/printOrder")
public class printOrder extends HttpServlet {
    private static final long serialVersionUID = 1L;

    final String EBussinessID = "";//kdniao.com EBusinessID
    final String AppKey = ""; //kdniao.com AppKey
    final Integer IsPreview = 0; //是否预览 0-不预览 1-预览

    /**
     * @see HttpServlet#HttpServlet()
     */
    public printOrder() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //response.getWriter().append("Served at: ").append(request.getContextPath());
        PrintWriter print = response.getWriter();
        String jsonResult = "";
        try {
            String ip = getIpAddress(request);
            jsonResult = getPrintParam(ip);
        } catch (Exception e) {
            //write log
        }
        print.println(jsonResult);
        print.flush();
        print.close();
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, UnsupportedEncodingException {
        // TODO Auto-generated method stub
        response.setContentType("");
        PrintWriter print = response.getWriter();
        String jsonResult = "";
        try {
            String ip = getIpAddress(request);
            jsonResult = getPrintParam(ip);
        } catch (Exception e) {
            //wirte log
        }
        print.println(jsonResult);
        print.flush();
        print.close();
    }

    /**
     * get print order param to json string
     * @return
     * 
     * @throws Exception 
     */
    private String getPrintParam(String ip) throws Exception {
        String data = "[{\"OrderCode\":\"234351215333113311353\",\"PortName\":\"SF\"},{\"OrderCode\":\"234351215333113311354\",\"PortName\":\"打印机名称二\"}]";
        String result = "{\"RequestData\": \"" + URLEncoder.encode(data, "UTF-8") + "\", \"EBusinessID\":\"" + EBussinessID + "\", \"DataSign\":\"" + encrpy(ip + data, AppKey) + "\", \"IsPreview\":\""
                        + IsPreview + "\"}";
        return result;
    }

    private String md5(String str, String charset) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes(charset));
        byte[] result = md.digest();
        StringBuffer sb = new StringBuffer(32);
        for (int i = 0; i < result.length; i++) {
            int val = result[i] & 0xff;
            if (val <= 0xf) {
                sb.append("0");
            }
            sb.append(Integer.toHexString(val));
        }
        return sb.toString().toLowerCase();
    }

    private String encrpy(String content, String key) throws UnsupportedEncodingException, Exception {
        String charset = "UTF-8";
        return new String(Base64.encode(md5(content + key, charset).getBytes(charset)));
    }

    /** 
     * 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址; 
     *  
     * @param request 
     * @return 
     * @throws IOException 
     */
    public final static String getIpAddress(HttpServletRequest request) throws IOException {
        // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址  

        String ip = request.getHeader("X-Forwarded-For");

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } else if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++) {
                String strIp = (String) ips[index];
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }
        return ip;
    }

}

 

 

 

但是,需要注意的是,API有一个ip参数,获取这个ip快递鸟提供的方法是如下

 

// 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址  
    public final static String getIpAddress(HttpServletRequest request) throws IOException {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } else if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++) {
                String strIp = (String) ips[index];
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }
        return ip;
    }

 

注意这个方法是没有问题的,但是你如果直接输入快递单号OrderCode进行打印,这个时候提交总是说数据验证不通过,并不是签名问题,而是ip问题。

因为上一个方法只要是在局域网下面,即使能访问外网,也没用,获取到的ip永远都是内网ip

有一种方式可以在本地验证通过,那就是直接百度ip,只有会有自己的ip地址

技术分享图片

OK,在后台将ip写死,就可以进行打印预览操作了。

打印需要安装lodop打印插件,安装完成之后访问 http://localhost:8000/CLodopfuncs.js 会有相应的控件js

需要对应的打印插件,必须要有设备(热敏打印机),要不我也不至于出差了。

之后根据打印机型号,进入对应的官网下载打印驱动。之后perfect,就可以进行打印了。

官方demo给的是servlet

我使用的是SpringMVC,将代码贴出。

final String EBussinessID = "12677**";//kdniao.com EBusinessID
    final String AppKey = "8e9dcb4b-f0a1-42f6-9d80-372a67f851**"; //kdniao.com AppKey
    final Integer IsPreview = 1; //是否预览 0-不预览 1-预览

    @RequestMapping("/getCloudPrintData.do")
    @ResponseBody
    public Map<String, Object> getCloudPrintData(HttpServletRequest request,String OrderCode,String ip) throws Exception{
        System.out.println("ok:"+OrderCode+"---"+ip);
        Map<String,Object> map = new HashMap<String, Object>();
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        Map<String,Object> dataMap = new HashMap<String, Object>();
        dataMap.put("OrderCode", OrderCode);
        dataMap.put("PortName", "Xprinter XP-DT108A LABEL");
        list.add(dataMap);
        String jsonString = JSONArray.fromObject(dataMap).toString();        
        map.put("RequestData", URLEncoder.encode(jsonString, "UTF-8"));
        if(StringUtils.isEmpty(ip)) {
            ip = getIpAddress(request);
        }
        map.put("DataSign",encrpy(ip + jsonString, AppKey));
        System.out.println("map:"+map);
        return map;
    }
    
    @RequestMapping("/getIpAddressByJava.do")
    @ResponseBody
    public String getIpAddressByJava(HttpServletRequest request) throws IOException {
        return getIpAddress(request);
    }
    
    private String encrpy(String content, String key) throws UnsupportedEncodingException, Exception {
        String charset = "UTF-8";
        return new String(Base64.encode(md5(content + key, charset).getBytes(charset)));
    }
    
    private String md5(String str, String charset) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes(charset));
        byte[] result = md.digest();
        StringBuffer sb = new StringBuffer(32);
        for (int i = 0; i < result.length; i++) {
            int val = result[i] & 0xff;
            if (val <= 0xf) {
                sb.append("0");
            }
            sb.append(Integer.toHexString(val));
        }
        return sb.toString().toLowerCase();
    }
    
    // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址  
    public final static String getIpAddress(HttpServletRequest request) throws IOException {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } else if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++) {
                String strIp = (String) ips[index];
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }
        return ip;
    }

 

 对应的html

<body>
<script type="text/javascript">
    function fasong(){
        var orderNo = $("#orderNo").val();
        var ipAddress = $("#ipAddress").val();
        $.ajax({
            url:/jeeadmin/jeecms/getCloudPrintData.do,
            data:{OrderCode:orderNo,ip:ipAddress},
            success:function(data){
                $("#RequestData").val(data.RequestData)
                $("#DataSign").val(data.DataSign)
            }
        })
    }
    function getIp(){
        $.ajax({
            url:/jeeadmin/jeecms/getIpAddressByJava.do,
            success:function(data){
                alert(data);
            }
        })
    }
</script>
<h1>测试打印页面</h1>
    <div id="head"></div>
    <div>
        <input type="text" id="orderNo">
        <input type="text" id="ipAddress">
        <input type="button" onclick="fasong()" value="发送" />
    </div>
    <div>
        <input type="button" onclick="getIp()" value="获取ip地址通过java"/>
    </div>
    <form id="form1" action="http://www.kdniao.com/External/PrintOrder.aspx" method="post" target="_self">
        <div style="">
            <div><input type="text" id="RequestData" name="RequestData" readonly="readonly"/>请求数据</div>
            <div><input type="text" id="DataSign" name="DataSign" readonly="readonly"/>签名</div>
            <div><input type="text" id="EBusinessID" name="EBusinessID" value="1267739"/>商户id</div>
            <div><input type="text" id="IsPreview" name="IsPreview" value="1"/><span style="color: red;">是否预览 0-不预览 1-预览</span></div>
            <div><input type="submit" id="tijiao" value="打印" /></div>
        </div>
    </form>
</body>

 lodop有云打印机,目前并不清楚,需要的话可以再研究下。

 年轻人,fighting!!!

 

 

 

 

快递鸟电子面单打印功能基于java

标签:进入   contex   sel   extend   注意   ipaddress   readonly   data   .data   

原文地址:https://www.cnblogs.com/c-h-y/p/9898614.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!