快递100实时查询接口C#

快递100实时查询接口C#版

官方文档其实已经能够实现业务了,不过老是有小白会说少东西。你们说的是“CreatePostHttpResponse”这个吧?ok,那我就把完整的代码贴出来。
我将api封装到我的方法里面,方法接收三个参数:物流公司编码、物流单号,还有订单id,当然订单id是我的业务需求,你们可以根据自己去求改。因为api好像是按次收费的,每天的查询次数也有限制、所以这里我们先检测我们自己服务器是否有了需要的物流信息,没有再去请求api。检测这一步你们可以不要,因为是我公司框架的东西,你们直接拿来用会报错的哈,直接删了就行。当然保存的部分也可以不要。其他就没什么了。

    /// 快递100实时查询API封装
    public object getWlInfo(string wlname,string wlcode,int Did)
    {           

        //检测数据库是否存在物流信息有则返回,没有则请求API
        Logistics log = ormDao.Get<Logistics>("*", "DID=? and IsCheck=?", Did, 1);
        if (log != null)
        {
            log.data = ormDao.Fd<OrderLogisticsMx>("*", "Lid=?", log.Lid);
            return log;
        }

        string url = "http://poll.kuaidi100.com/poll/query.do";
        Encoding encoding = Encoding.GetEncoding("utf-8");

        //参数
        String param = "{\"com\":\"" + wlname + "\",\"num\":\"" + wlcode + "\"}";
        YiTian.dyc.orm.SysParam syspa = SysConfigManage.getParam(SysConfigManage.getConfig().orgcode,2016,"","");
        String customer = syspa.POValue;
        String key = syspa.PValue;
        MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
        byte[] InBytes = Encoding.GetEncoding("UTF-8").GetBytes(param + key + customer);
        byte[] OutBytes = md5.ComputeHash(InBytes);
        string OutString = "";
        for (int i = 0; i < OutBytes.Length; i++)
        {
            OutString += OutBytes[i].ToString("x2");
        }
        String sign = OutString.ToUpper();
        IDictionary parameters = new Dictionary<string, string>();
        parameters.Add("param", param);
        parameters.Add("customer", customer);
        parameters.Add("sign", sign);
        HttpWebResponse response = CreatePostHttpResponse(url, parameters, encoding);
        //打印返回值
        Stream stream = response.GetResponseStream();   //获取响应的字符串流
        StreamReader sr = new StreamReader(stream); //创建一个stream读取流
        string html = sr.ReadToEnd();   //从头读到尾,放到字符串html
        Dictionary<string, object> oo = null;
        if (string.IsNullOrEmpty(html) == false)
        {
            oo = StringUtil.toDictByJson(html);
        }
        oo.Add("ComName", dname);

        //检测是否已签收,是则将数据保存至数据库
        if (oo["ischeck"].Equals("1"))
        {
            OrderLogistics s = new OrderLogistics();
            s.Nu = wlcode;
            s.Did = Did;
            s.Com = wlname;
            s.state = int.Parse(oo["state"]+"");
            s.status = oo["status"] + "";
            s.ComName = dname;
            ormDao.Add(s);

            foreach(string p in oo.Keys)
            {
                if (p.Contains("data"))
                {
                    List<Dictionary<string, object>> Dit = (List<Dictionary<string, object>>)oo["data"];
                    for (int i = 0; i < Dit.Count;i++ )
                    {
                        OrderLogisticsMx mx = new OrderLogisticsMx()
                        { 
                            Lid = s.Lid,
                            time = Dit[i]["time"]+"",
                            ftime = Dit[i]["ftime"]+"",
                            context = Dit[i]["context"]+""
                        };
                        ormDao.Add(mx);
                    }
                }
            }
        }
        return oo;
    }

    private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";

    private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
    {
        return true; //总是接受   
    }

    internal static HttpWebResponse CreatePostHttpResponse(string url, System.Collections.IDictionary parameters, Encoding encoding)
    {
        HttpWebRequest request = null;
        //HTTPSQ请求
        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
        request = WebRequest.Create(url) as HttpWebRequest;
        request.ProtocolVersion = HttpVersion.Version10;
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.UserAgent = DefaultUserAgent;
        //如果需要POST数据   
        if (!(parameters == null || parameters.Count == 0))
        {
            StringBuilder buffer = new StringBuilder();
            int i = 0;
            foreach (string key in parameters.Keys)
            {
                if (i > 0)
                {
                    buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                }
                else
                {
                    buffer.AppendFormat("{0}={1}", key, parameters[key]);
                }
                i++;
            }
            byte[] data = System.Text.Encoding.Default.GetBytes(buffer.ToString());
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
        }
        return request.GetResponse() as HttpWebResponse;
    }
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jain_k

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值