快递查询 C#分分快三计划

作者:编程技术

        /// <summary>  
        /// 将对象属性转换为key-value对  
        /// </summary>  
        /// <param name="o"></param>  
        /// <returns></returns>  
        private static Dictionary<String, String> ToMap(Object o)
        {
            Dictionary<String, String> map = new Dictionary<String, String>();

/// <summary>
/// base64编码
/// </summary>
/// <param name="str">内容</param>
/// <param name="charset">编码方式</param>
/// <returns></returns>
private string base64(String str, String charset)
{
return Convert.ToBase64String(System.Text.Encoding.GetEncoding.GetBytes;
}

                StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream(),
                    System.Text.Encoding.GetEncoding("utf-8"));

        }
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="input">字符串</param>
        /// <returns></returns>
        public static string GetMd5Hash(string input)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.

//电商ID
private string EBusinessID = "1257164";
//电商加密私钥,快递鸟提供,注意保管,不要泄漏
private string AppKey = "63a33b7c-464c-4de6-b4a3-6e1fc19da51c";
//请求url
private string ReqURL = "";

            return parameters;
        }

            // Return the hexadecimal string.

///<summary>
/// 字符串MD5加密
///</summary>
///<param name="str">要加密的字符串</param>
///<param name="charset">编码方式</param>
///<returns>密文</returns>
private string MD5(string str, string charset)
{
byte[] buffer = System.Text.Encoding.GetEncoding.GetBytes;
try
{
System.Security.Cryptography.MD5CryptoServiceProvider check;
check = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] somme = check.ComputeHash;
string ret = "";
foreach (byte a in somme)
{
if (a < 16)
ret = "0" a.ToString;
else
ret = a.ToString;
}
return ret.ToLower();
}
catch
{
throw;
}
}

                return httpWebResponse;
            } catch {
                callback(null);
            }
            return null;
        }

            // Convert the input string to a byte array and compute the hash.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create;
request.ContentType = "application/x-www-form-urlencoded";
request.Referer = url;
request.Accept = "*/*";
request.Timeout = 30 * 1000;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
request.Method = "POST";
request.ContentLength = byteData.Length;
Stream stream = request.GetRequestStream();
stream.Write(byteData, 0, byteData.Length);
stream.Flush();
stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream backStream = response.GetResponseStream();
StreamReader sr = new StreamReader(backStream, Encoding.GetEncoding;
result = sr.ReadToEnd();
sr.Close();
backStream.Close();
response.Close();
request.Abort();
}
catch (Exception ex)
{
result = ex.Message;
}
return result;
}

                StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream(),
                    System.Text.Encoding.GetEncoding(encoding));

            for (int i = 0; i < data.Length; i )
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

/// <summary>
/// Post方式提交数据,返回网页的源代码
/// </summary>
/// <param name="url">发送请求的 URL</param>
/// <param name="param">请求的参数集合</param>
/// <returns>远程资源的响应结果</returns>
private string sendPost(string url, Dictionary<string, string> param)
{
string result = "";
StringBuilder postData = new StringBuilder();
if (param != null && param.Count > 0)
{
foreach (var p in param)
{
if (postData.Length > 0)
{
postData.Append;
}
postData.Append;
postData.Append;
postData.Append;
}
}
byte[] byteData = Encoding.GetEncoding.GetBytes(postData.ToString;
try
{

        /// <summary>  
        /// 创建GET方式的HTTP请求  
        /// </summary>  
        /// <param name="url">请求的URL</param>  
        /// <param name="timeout">请求的超时时间</param>  
        /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>  
        /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>  
        /// <returns></returns>  
        private static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent,
            CookieCollection cookies, Action<string> callback, string encoding = "utf-8") {
            if (string.IsNullOrEmpty(url)) {
                return null;
                //throw new ArgumentNullException("url");
            }
            try {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "GET";
                request.UserAgent = DefaultUserAgent;
                if (!string.IsNullOrEmpty(userAgent)) {
                    request.UserAgent = userAgent;
                }
                if (timeout.HasValue) {
                    request.Timeout = timeout.Value;
                }
                if (cookies != null) {
                    request.CookieContainer = new CookieContainer();
                    request.CookieContainer.Add(cookies);
                }

            // Create a new Stringbuilder to collect the bytes

#endregion
string typeCom = "";
foreach (var dc in list)
{
if (com == dc.Key)
{
typeCom = dc.Value;
}
}
string requestData = "{OrderCode:'',ShipperCode:'" typeCom "','LogisticCode':'" nu "'}";

                if (!string.IsNullOrEmpty(userAgent)) {
                    request.UserAgent = userAgent;
                } else {
                    request.UserAgent = DefaultUserAgent;
                }

        public static string api_secret { get; set; }

///<summary>
///电商Sign签名
///</summary>
///<param name="content">内容</param>
///<param name="keyValue">Appkey</param>
///<param name="charset">URL编码 </param>
///<returns>DataSign签名</returns>
private string encrypt(String content, String keyValue, String charset)
{
if (keyValue != null)
{
return base64(MD5(content keyValue, charset), charset);
}
return base64(MD5(content, charset), charset);
}

                if (timeout.HasValue) {
                    request.Timeout = timeout.Value;
                }
                if (cookies != null) {
                    request.CookieContainer = new CookieContainer();
                    request.CookieContainer.Add(cookies);
                }
                //如果需要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 = requestEncoding.GetBytes(buffer.ToString());
                    using (Stream stream = request.GetRequestStream()) {
                        stream.Write(data, 0, data.Length);
                    }
                }

            MD5 md5Hasher = MD5.Create();

string result = sendPost(ReqURL, param);

                //关闭
                httpWebResponse.Close();
                reader.Close();

            // and format each one as a hexadecimal string.

/// <summary>
/// Json方式 查询订单物流轨迹
/// </summary>
/// <returns></returns>
public string postkuaidi(string com, string nu)
{
Dictionary<string, string> list = new Dictionary<string, string>();
#region 快递
list.Add("邮政平邮", "YZPY");
list.Add("邮政国内", "YZPY");
list.Add("中国邮政", "YZPY");
list.Add("申通快递", "STO");

                StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream(),
                    System.Text.Encoding.GetEncoding("utf-8"));

            Type t = o.GetType();

Dictionary<string, string> param = new Dictionary<string, string>();
param.Add("RequestData", HttpUtility.UrlEncode(requestData, Encoding.UTF8));
param.Add("EBusinessID", EBusinessID);
param.Add("RequestType", "1002");
string dataSign = encrypt(requestData, AppKey, "UTF-8");
param.Add("DataSign", HttpUtility.UrlEncode(dataSign, Encoding.UTF8));
param.Add("DataType", "2");

namespace WXCustomerCard.Code {
    public class HttpQuery {
        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)";

       /// <summary>
        /// 校验签名
        /// </summary>
        /// <param name="model">实体</param>
        /// <param name="sign">签名</param>
        /// <returns></returns>
        public static bool CheckSign(object model, string sign)
        {
            SortedDictionary<string, string> signParams = new SortedDictionary<string, string>(StringComparer.Ordinal);
            var keyValueTo = ToMap(model);
            foreach (var p in keyValueTo)
            {
                if (p.Key != "Sign" && p.Key != "Signlen" && p.Key != "Img")
                {
                    signParams[p.Key] = p.Value;
                }
            }
            StringBuilder paramStr = new StringBuilder();
            foreach (var item in signParams)
            {
                if (string.IsNullOrWhiteSpace(item.Value) == false)
                {
                    paramStr.AppendFormat("{0}={1}&", item.Key, item.Value);
                }
            }
            paramStr.AppendFormat("Key={0}", api_secret);
            string computeSign = GetMd5Hash(paramStr.ToString()).ToUpper();
            return string.Equals(sign, computeSign);
        }
        /// <summary>
        /// 生成签名
        /// </summary>
        /// <param name="model">实体</param>
        /// <returns></returns>
        public static string GetSign(object model)
        {
            SortedDictionary<string, string> signParams = new SortedDictionary<string, string>(StringComparer.Ordinal);
            var keyValueTo = ToMap(model);
            foreach (var p in keyValueTo)
            {
                if (p.Key != "Sign" && p.Key != "Signlen" && p.Key != "Img")
                {
                    signParams[p.Key] = p.Value;
                }
            }
            StringBuilder paramStr = new StringBuilder();
            foreach (var item in signParams)
            {
                if (string.IsNullOrWhiteSpace(item.Value) == false)
                {
                    paramStr.AppendFormat("{0}={1}&", item.Key, item.Value);
                }
            }
            paramStr.AppendFormat("Key={0}", api_secret);
            string computeSign = GetMd5Hash(paramStr.ToString()).ToUpper();
            return computeSign;
        }

//根据公司业务处理返回的信息......
JObject jo = JObject.Parse;
return jo.ToString();
}

                HttpWebResponse httpWebResponse = request.GetResponse() as HttpWebResponse;

            byte[] data = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(input));

                Regex regex = new Regex("charset=(?<code>\w )"");
                Match match = regex.Match(html);
                string code = match.Groups["code"].Value;
                if (!string.IsNullOrWhiteSpace(code) && code.ToLower() != encoding.ToLower()) {
                    return CreateGetHttpResponse(url, timeout, userAgent, cookies, callback, code);
                } else {
                    callback(html);
                    return httpWebResponse;
                }
            } catch {
                callback(null);
            }
            return null;
        }

            // and create a string.

            Type type = data.GetType();
            PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo p in props) {
                parameters.Add(p.Name, p.GetValue(data).ToString());
            }

            foreach (PropertyInfo p in pi)
            {
                MethodInfo mi = p.GetGetMethod();

                if (!string.IsNullOrEmpty(userAgent)) {
                    request.UserAgent = userAgent;
                } else {
                    request.UserAgent = DefaultUserAgent;
                }

            // Loop through each byte of the hashed data

                string html = "";
                //获取请求到的数据
                html = reader.ReadToEnd();

                if (mi != null && mi.IsPublic)
                {
                    map.Add(p.Name, mi.Invoke(o, new String[] { }).ToString());
                }
            }

                string html = "";
                //获取请求到的数据
                html = reader.ReadToEnd();

            StringBuilder sBuilder = new StringBuilder();

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Text;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Reflection;
using System.Text.RegularExpressions;

            return sBuilder.ToString();
        }

        public static void Post(string url, object data, Action<string> callback) {
            IDictionary<string, string> parameters = Getparameters(data);

            return map;

        private static IDictionary<string, string> Getparameters(object data) {
            if (data == null) {
                return new Dictionary<string, string>();
            }
            IDictionary<string, string> parameters = new Dictionary<string, string>();

            PropertyInfo[] pi = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);

        public static void Post(string url, string data, Action<string> callback) {
            CreatePostHttpResponse(url, data, null, null, Encoding.UTF8, null, callback);
        }

        private static HttpWebResponse CreatePostHttpResponse(string url, string parameters, int? timeout,
            string userAgent, Encoding requestEncoding, CookieCollection cookies, Action<string> callback) {
            if (string.IsNullOrEmpty(url)) {
                return null;
                //throw new ArgumentNullException("url");
            }
            if (requestEncoding == null) {
                throw new ArgumentNullException("requestEncoding");
            }
            HttpWebRequest request = null;
            try {
                //如果是发送HTTPS请求  
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) {
                    ServicePointManager.ServerCertificateValidationCallback =
                        new RemoteCertificateValidationCallback(CheckValidationResult);
                    request = WebRequest.Create(url) as HttpWebRequest;
                    request.ProtocolVersion = HttpVersion.Version10;
                } else {
                    request = WebRequest.Create(url) as HttpWebRequest;
                }
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";

        /// <summary>  
        /// 创建POST方式的HTTP请求  
        /// </summary>  
        /// <param name="url">请求的URL</param>  
        /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>  
        /// <param name="timeout">请求的超时时间</param>  
        /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>  
        /// <param name="requestEncoding">发送HTTP请求时所用的编码</param>  
        /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>  
        /// <returns></returns>  
        private static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters,
            int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies, Action<string> callback) {
            if (string.IsNullOrEmpty(url)) {
                throw new ArgumentNullException("url");
            }
            if (requestEncoding == null) {
                throw new ArgumentNullException("requestEncoding");
            }
            HttpWebRequest request = null;
            try {
                //如果是发送HTTPS请求  
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) {
                    ServicePointManager.ServerCertificateValidationCallback =
                        new RemoteCertificateValidationCallback(CheckValidationResult);
                    request = WebRequest.Create(url) as HttpWebRequest;
                    request.ProtocolVersion = HttpVersion.Version10;
                } else {
                    request = WebRequest.Create(url) as HttpWebRequest;
                }
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";

            CreatePostHttpResponse(url, parameters, null, null, Encoding.UTF8, null, callback);
        }
        public static void Post(string url, IDictionary<string, string> data, Action<string> callback) {
            CreatePostHttpResponse(url, data, null, null, Encoding.UTF8, null, callback);
        }

                return httpWebResponse;
            } catch {
                callback(null);
            }
            return null;
        }

                //关闭
                httpWebResponse.Close();
                reader.Close();

        public static void Get(string url, object data, Action<string> callback) {
            IDictionary<string, string> parameters = Getparameters(data);

                if (timeout.HasValue) {
                    request.Timeout = timeout.Value;
                }
                if (cookies != null) {
                    request.CookieContainer = new CookieContainer();
                    request.CookieContainer.Add(cookies);
                }
                //如果需要POST数据  
                if (!string.IsNullOrEmpty(parameters)) {
                    using (var streamWriter = new StreamWriter(request.GetRequestStream())) {
                        streamWriter.Write(parameters);
                        streamWriter.Flush();
                    }
                }

                HttpWebResponse httpWebResponse = request.GetResponse() as HttpWebResponse;

        public JsonResult Orders( ) {
            string json = "";
            string url = string.Format("www.baidu.com”);
            HttpQuery.Get(url, null, msg => {
                json = msg;
            });
            if (json != "") {
                return Json(json);
            }
            return Json("");
        }

            if (!(parameters == null || parameters.Count == 0)) {
                url = "?";
                foreach (var item in parameters) {
                    url = item.Key "=" item.Value "&";
                }
            }
            CreateGetHttpResponse(url, null, null, null, callback);
        }

                string html = "";
                //获取请求到的数据
                html = reader.ReadToEnd();
                //关闭
                httpWebResponse.Close();
                reader.Close();

                HttpWebResponse httpWebResponse = request.GetResponse() as HttpWebResponse;

                callback(html);

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

 

                callback(html);

本文由分分快三计划发布,转载请注明来源

关键词: 分分快三计划 快递