Java常用工具类-根据物流单号,从快递100中获取物流详细信息

根据物流单号,从快递100中获取物流详细信息。

快递100测试入口:

public class Kuaidi100 {
    public Kuaidi100() {
    }

    public static void main(String[] args) throws Exception {
        String str = getKuaidiURL("zhongtong", "701210536113");
        System.out.println(str);
        JSONObject jsonStu = JSONObject.fromObject(str);
        Logistics100VO logistics100VO = (Logistics100VO)JSONObject.toBean(jsonStu, Logistics100VO.class);
        System.out.println(logistics100VO);
        List list = logistics100VO.getData();

        for(int i = 0; i < list.size(); ++i) {
            MorphDynaBean logisticsDataVO = (MorphDynaBean)list.get(i);
            System.out.println(logisticsDataVO.get("time"));
        }

    }

    public static String getKuaidiURL(String com, String nu) {
        Object urlStream = null;

        try {
            URL url = new URL("http://www.kuaidi100.com/query?type=" + com + "&postid=" + nu);
            URLConnection con = url.openConnection();
            con.setAllowUserInteraction(false);
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF8"));
            StringBuffer bankXmlBuffer = new StringBuffer();

            String inputLine;
            while((inputLine = in.readLine()) != null) {
                bankXmlBuffer.append(inputLine);
            }

            in.close();
            String var9 = bankXmlBuffer.toString();
            return var9;
        } catch (MalformedURLException var19) {
            var19.printStackTrace();
        } catch (IOException var20) {
            var20.printStackTrace();
        } finally {
            if (urlStream != null) {
                try {
                    ((InputStream)urlStream).close();
                } catch (IOException var18) {
                    var18.printStackTrace();
                }
            }

        }

        return null;
    }

    public static String getKuaidiStr(String com, String nu) {
        Object urlStream = null;

        try {
            URL url = new URL("http://api.kuaidi100.com/api?id=*****&com=" + com + "&nu=" + nu + "&show=0&muti=1&order=desc");
            URLConnection con = url.openConnection();
            con.setAllowUserInteraction(false);
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF8"));
            StringBuffer bankXmlBuffer = new StringBuffer();

            String inputLine;
            while((inputLine = in.readLine()) != null) {
                bankXmlBuffer.append(inputLine);
            }

            in.close();
            String var9 = bankXmlBuffer.toString();
            return var9;
        } catch (MalformedURLException var19) {
            var19.printStackTrace();
        } catch (IOException var20) {
            var20.printStackTrace();
        } finally {
            if (urlStream != null) {
                try {
                    ((InputStream)urlStream).close();
                } catch (IOException var18) {
                    var18.printStackTrace();
                }
            }

        }

        return null;
    }
}

快递100工具类如下:

public class Kuaidi100Util {

   /**
    * 从快递100中获取物流信息
    * 
    * @param logisticsCompanyName物流公司名
    * @param trackingNumber物流单号
    * @return
    */
   public static Logistics100VO getNewLogistics(String logisticsCompanyName,
         String trackingNumber) {
      /*
       * String logisticsCompanyShort =
       * getLogisticsCompanyShort(logisticsCompanyName); if
       * (logisticsCompanyShort == null) { return null; }
       */
      JSONObject jsonStu = JSONObject.fromObject(Kuaidi100.getKuaidiURL(
            logisticsCompanyName, trackingNumber));
      return (Logistics100VO) JSONObject
            .toBean(jsonStu, Logistics100VO.class);
   }

   /**
    * 根据物流公司,获取快递100中的物流公司简称.
    * 
    * @param company
    *            String
    * @return
    */
   public static String getLogisticsCompanyShort(String company) {
      if(StringUtil.isNull(company)){
         return null;
      }
      String shortName = null;
      if (company.indexOf("包裹") >= 0 || company.indexOf("平邮") >= 0) {
         shortName = "youzhengguonei";
      } else if (company.toLowerCase().indexOf("ems") >= 0) {
         shortName = "ems";
      } else if (company.toLowerCase().indexOf("北京ems") >= 0) {
         shortName = "bjemstckj";
      } else if (company.indexOf("顺丰") >= 0) {
         shortName = "shunfeng";
      } else if (company.indexOf("申通") >= 0) {
         shortName = "shentong";
      } else if (company.indexOf("圆通") >= 0) {
         shortName = "yuantong";
      } else if (company.indexOf("中通") >= 0) {
         shortName = "zhongtong";
      } else if (company.indexOf("汇通") >= 0) {
         shortName = "huitongkuaidi";
      } else if (company.indexOf("韵达") >= 0) {
         shortName = "yunda";
      } else if (company.indexOf("宅急送") >= 0) {
         shortName = "zhaijisong";
      } else if (company.indexOf("天天") >= 0) {
         shortName = "tiantian";
      } else if (company.indexOf("德邦") >= 0) {
         shortName = "debangwuliu";
      } else if (company.indexOf("国通") >= 0) {
         shortName = "guotongkuaidi";
      } else if (company.indexOf("增益") >= 0) {
         shortName = "zengyisudi";
      } else if (company.indexOf("速尔") >= 0) {
         shortName = "suer";
      } else if (company.indexOf("中铁物流") >= 0) {
         shortName = "ztky";
      } else if (company.indexOf("中铁快运") >= 0) {
         shortName = "zhongtiewuliu";
      } else if (company.indexOf("能达") >= 0) {
         shortName = "ganzhongnengda";
      } else if (company.indexOf("优速") >= 0) {
         shortName = "youshuwuliu";
      } else if (company.indexOf("全峰") >= 0) {
         shortName = "quanfengkuaidi";
      } else if (company.indexOf("京东") >= 0) {
         shortName = "jd";
      } else if (company.indexOf("一统飞鸿") >= 0) {
         shortName = "yitongfeihong";
      } else if (company.indexOf("如风达") >= 0) {
         shortName = "rufengda";
      } else if (company.indexOf("赛澳递") >= 0) {
         shortName = "saiaodi";
      } else if (company.indexOf("海红网送") >= 0) {
         shortName = "haihongwangsong";
      } else if (company.indexOf("通和天下") >= 0) {
         shortName = "tonghetianxia";
      } else if (company.indexOf("郑州建华") >= 0) {
         shortName = "zhengzhoujianhua";
      } else if (company.indexOf("红马甲") >= 0) {
         shortName = "sxhongmajia";
      } else if (company.indexOf("芝麻开门") >= 0) {
         shortName = "zhimakaimen";
      } else if (company.indexOf("乐捷递") >= 0) {
         shortName = "lejiedi";
      } else if (company.indexOf("立即送") >= 0) {
         shortName = "lijisong";
      } else if (company.indexOf("银捷") >= 0) {
         shortName = "yinjiesudi";
      } else if (company.indexOf("门对门") >= 0) {
         shortName = "menduimen";
      } else if (company.indexOf("河北建华") >= 0) {
         shortName = "hebeijianhua";
      } else if (company.indexOf("微特派") >= 0) {
         shortName = "weitepai";
      } else if (company.indexOf("风行天下") >= 0) {
         shortName = "fengxingtianxia";
      } else if (company.indexOf("尚橙") >= 0) {
         shortName = "shangcheng";
      } else if (company.indexOf("新蛋奥硕") >= 0) {
         shortName = "neweggozzo";
      }
      return shortName;
   }

   public static void main(String[] args) throws Exception {
      String str = Kuaidi100.getKuaidiURL("zhongtong", "701210536113");
      System.out.println(str);
      JSONObject jsonStu = JSONObject.fromObject(str);
      Logistics100VO logistics100VO = (Logistics100VO) JSONObject.toBean(
            jsonStu, Logistics100VO.class);
      System.out.println(logistics100VO);
      List list = logistics100VO.getData();
      for (int i = 0; i < list.size(); i++) {
         net.sf.ezmorph.bean.MorphDynaBean logisticsDataVO = (net.sf.ezmorph.bean.MorphDynaBean) list
               .get(i);
         System.out.println(logisticsDataVO.get("time"));
      }

   }

   /**
    * 向快递100发送订阅物流单号信息
    * 
    * @param companycode
    *            物流公司code-- 非必填,空时将使用autoCom=1进行智能判断物流公司
    * @param number
    *            物流单号-- 必填
    * @param from
    *            出发地-- 非必填
    * @param to
    *            终点-- 非必填
    * @param salt
    *            数字签名-- 非必填
    * */
   public static TaskResponse postOrder(String companycode, String number,
         String from, String to, String salt) {
      TaskResponse resp = new TaskResponse();
      ConfigVO vo = ConfigUtil.getInstance().getConfigVO();
      if (!vo.isOpenkuaidi100()) {
         resp.setResult(false);
         resp.setMessage("快递100订阅服务未开启");
         return resp;
      }
      if (StringUtil.isNull(vo.getKuaidi100server())
            || StringUtil.isNull(vo.getKuaidi100callback())
            || StringUtil.isNull(vo.getKuaidi100authkey())) {
         resp.setResult(false);
         resp.setMessage("快递100订阅服务参数配置错误");
         return resp;
      }
      if (StringUtil.isNull(number)) {
         resp.setResult(false);
         resp.setMessage("缺少物流单号");
         return resp;
      }
      if (StringUtil.isNull(salt)) {
         resp.setResult(false);
         resp.setMessage("缺少验证签名");
         return resp;
      }
      TaskRequest req = new TaskRequest();
      req.setCompany(companycode);
      req.setFrom(from == null ? "" : from);
      req.setTo(to == null ? "" : to);
      req.setNumber(number);
      req.getParameters().put("callbackurl", vo.getKuaidi100callback());
      req.getParameters().put("salt", salt);// 签名
      if (StringUtil.isNull(companycode)) {
         req.getParameters().put("autoCom", "1");// companycode为空时智能判断物流公司
      }
      req.setKey(vo.getKuaidi100authkey());

      Gson gson = new Gson();

      HashMap<String, String> p = new HashMap<String, String>();
      p.put("schema", "json");
      p.put("param", gson.toJson(req));
      try {
         String ret = HttpRequest.postData(vo.getKuaidi100server(), p,
               "UTF-8");
         resp = gson.fromJson(ret, TaskResponse.class);
         return resp;
      } catch (Exception e) {
         e.printStackTrace();
         resp = new TaskResponse();
         resp.setResult(false);
         resp.setMessage("向快递100发送订阅物流单号信息异常,原因:" + e.getMessage());
         return resp;
      }
   }

   // 根据物流单号猜测快递公司
   public static String caiceComcode(String number) {
      if (StringUtil.isNull(number)) {
         return "";
      }
      ConfigVO vo = ConfigUtil.getInstance().getConfigVO();
      if (StringUtil.isNull(vo.getKuaidi100authkey())) {
         return "";
      }
      HashMap<String, String> p = new HashMap<String, String>();
      p.put("num", number);
      p.put("key", vo.getKuaidi100authkey());
      try {
         String ret = HttpRequest.postData(
               "http://www.kuaidi100.com/autonumber/auto", p, "UTF-8");
         if (StringUtil.isNull(ret)) {
            return "";
         }
         List<Map<String, Object>> comcodes = new ArrayList<Map<String, Object>>();
         comcodes = new Gson().fromJson(ret,
               new TypeToken<List<Map<String, Object>>>() {
               }.getType());
         if (comcodes == null || comcodes.size() == 0) {
            return "";
         }
         return comcodes.get(0).get("comCode").toString();
      } catch (Exception e) {
         e.printStackTrace();
         return "";
      }
   }
}

实体类Logistics100VO:

public class Logistics100VO {
    private String nu;
    private String message;
    private String comcontact;
    private String ischeck;
    private String com;
    private String condition;
    private String status;
    private String state;
    private List<LogisticsDataVO> data;

    public Logistics100VO() {
    }

    public String getNu() {
        return this.nu;
    }

    public void setNu(String nu) {
        this.nu = nu;
    }

    public String getMessage() {
        return this.message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getComcontact() {
        return this.comcontact;
    }

    public void setComcontact(String comcontact) {
        this.comcontact = comcontact;
    }

    public String getIscheck() {
        return this.ischeck;
    }

    public void setIscheck(String ischeck) {
        this.ischeck = ischeck;
    }

    public String getCom() {
        return this.com;
    }

    public void setCom(String com) {
        this.com = com;
    }

    public String getCondition() {
        return this.condition;
    }

    public void setCondition(String condition) {
        this.condition = condition;
    }

    public String getStatus() {
        return this.status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getState() {
        return this.state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public List<LogisticsDataVO> getData() {
        return this.data;
    }

    public void setData(List<LogisticsDataVO> data) {
        this.data = data;
    }

    public String toString() {
        return "nu=" + this.nu + ";message=" + this.message + ";comcontact=" + this.comcontact + ";ischeck=" + this.ischeck + ";com=" + this.com + ";condition=" + this.condition + ";status=" + this.status + ";state=" + this.state + ";data=" + this.data;
    }
}

 实体类TaskRequest:

public class TaskRequest {
   private static XStream xstream;
   private String company;
   private String number;
   private String from;
   private String to;
   private String key;
   private String src;

   private HashMap<String, String> parameters = new HashMap<String, String>();

   public String getCompany() {
      return company;
   }

   public void setCompany(String company) {
      this.company = company;
   }

   public String getNumber() {
      return number;
   }

   public void setNumber(String number) {
      this.number = number;
   }

   public String getFrom() {
      return from;
   }

   public void setFrom(String from) {
      this.from = from;
   }

   public String getTo() {
      return to;
   }

   public void setTo(String to) {
      this.to = to;
   }

   public String getKey() {
      return key;
   }

   public void setKey(String key) {
      this.key = key;
   }

   public String getSrc() {
      return src;
   }

   public void setSrc(String src) {
      this.src = src;
   }

   public HashMap<String, String> getParameters() {
      return parameters;
   }

   public void setParameters(HashMap<String, String> parameters) {
      this.parameters = parameters;
   }

   @Override
   public String toString() {
      return JacksonHelper.toJSON(this);
   }
   

   private static XStream getXStream() {
      if (xstream == null) {
         xstream = new XStream();
         xstream.registerConverter(new MapCustomConverter(new DefaultMapper(XStream.class.getClassLoader())));  
         xstream.autodetectAnnotations(true);
         xstream.alias("orderRequest", TaskRequest.class);
         xstream.alias("property", Entry.class);  
      }
      return xstream;
   }

   public String toXml(){
      return "<?xml version='1.0' encoding='UTF-8'?>\r\n" + getXStream().toXML(this);
   }

   public static TaskRequest fromXml(String sXml){
      return (TaskRequest)getXStream().fromXML(sXml);
   }

}

实体类TaskResponse:

public class TaskResponse {
   private static XStream xstream;
   private Boolean result;
   private String returnCode;
   private String message;

   public Boolean getResult() {
      return result;
   }

   public void setResult(Boolean result) {
      this.result = result;
   }

   public String getReturnCode() {
      return returnCode;
   }

   public void setReturnCode(String returnCode) {
      this.returnCode = returnCode;
   }

   public String getMessage() {
      return message;
   }

   public void setMessage(String message) {
      this.message = message;
   }

   private static XStream getXStream() {
      if (xstream == null) {
         xstream = new XStream();
         xstream.autodetectAnnotations(true);
         xstream.alias("orderResponse", TaskResponse.class);
      }
      return xstream;
   }

   public String toXml(){
      return "<?xml version='1.0' encoding='UTF-8'?>\r\n" + getXStream().toXML(this);
   }

   public static TaskResponse fromXml(String sXml){
      return (TaskResponse)getXStream().fromXML(sXml);
   }

   public static void main(String[] args){
      TaskResponse req = new TaskResponse();
      req.setMessage("订阅成功");
      req.setResult(true);
      req.setReturnCode("200");
      System.out.print(req.toXml());
   }

}

猜你喜欢

转载自blog.csdn.net/jlq_diligence/article/details/88866538