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

namespace ztotest
{
    class Program
    {
        static void Main(string[] args)
        {
            string company_id = "kfpttestCode";
            string key = "kfpttestkey==";
            string data = "{\"unionCode\":\"536178917071\",\"send_province\":\"上海市\",\"send_city\":\"上海市\",\"send_district\":\"青浦区\",\"send_address\":\"华新镇华志路123号\",\"receive_province\":\"四川省\",\"receive_city\":\"成都市\",\"receive_district\":\"武侯区\",\"receive_address\":\"610号和兴润园二期1栋2单元1003室\"}";
            var bodyNvc = new NameValueCollection();
            bodyNvc.Add("company_id", company_id);
            bodyNvc.Add("msg_type", "GETMARK");
            bodyNvc.Add("data", data);
            // 这里生成签名的body字符串的拼接顺序,要和http请求的参数顺序一致,也就是和上面bodyNvc的添加顺序一致
            string body = "company_id=" + company_id + "&msg_type=GETMARK" + "&data=" + data;
            var headersNvc = new NameValueCollection();
            headersNvc.Add("x-companyId", company_id);
            //得到签名
            string dataDigest = EncryptMD5Base64(body + key);
            headersNvc.Add("x-dataDigest", dataDigest);
            Console.WriteLine(CreatePostSysHttpResponse("http://58.40.16.120:9001/bagAddrMarkGetmark", headersNvc, bodyNvc, 5000, Encoding.UTF8, null));
        }



        /// <summary>
        /// 调用接口的方法
        /// </summary>
        /// <param name="url">调用的接口地址</param>
        /// <param name="postValues">参数集合</param>
        /// <returns></returns>
        public static string Redirect(string url, NameValueCollection postValues)
        {
            // -- 需要调用的接口 ---
            var request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            SetWebRequest(request);
            var data = EncodePars(postValues);
            WriteRequestData(request, data);
            var response = request.GetResponse() as HttpWebResponse;
            var responseStream = response.GetResponseStream();
            var encoding = new UTF8Encoding(false);
            var reader = new System.IO.StreamReader(responseStream, encoding);
            var rValue = reader.ReadToEnd();
            reader.Close();
            responseStream.Close();

            return rValue;
        }

        #region 创建POST方式的HTTP请求
        /// <summary>
        /// 创建POST方式的HTTP请求
        /// </summary>
        /// <param name="url">请求的URL</param>
        /// <param name="Hederparameters"></param>
        /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>
        /// <param name="timeout">请求的超时时间</param>
        /// <param name="requestEncoding">发送HTTP请求时所用的编码</param>
        /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
        /// <param name="contentType">请求的发送编码方式</param>
        /// <param name="method">请求的方式GET、POST</param>
        /// <returns></returns>
        public static string CreatePostSysHttpResponse(string url, NameValueCollection Hederparameters, NameValueCollection parameters, int? timeout, Encoding requestEncoding, CookieCollection cookies, string contentType = "application/x-www-form-urlencoded", string method = "POST")
        {
            string returns = "";
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            if (requestEncoding == null)
            {
                throw new ArgumentNullException("requestEncoding");
            }
            HttpWebRequest request = null;
            //如果是发送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 = method;
            request.ContentType = contentType;
            if (Hederparameters != null)
            {
                request.Headers.Add(Hederparameters);
            }
            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, HttpUtility.UrlEncode(parameters[key],Encoding.UTF8));
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, HttpUtility.UrlEncode(parameters[key],Encoding.UTF8));
                    }
                    i++;
                }
                byte[] data = requestEncoding.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            Stream responseStream = response.GetResponseStream();
            System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, requestEncoding);
            string ret = reader.ReadToEnd();
            reader.Close();
            responseStream.Close();
            returns = ret;
            return returns;
        }

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




        #region 帮助方法
        /// <summary>
        /// 设置请求的参数信息
        /// </summary>
        /// <param name="request"></param>
        private static void SetWebRequest(HttpWebRequest request)
        {
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Timeout = 10000;
        }
        /// <summary>
        /// 请求数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="data"></param>
        private static void WriteRequestData(HttpWebRequest request, byte[] data)
        {
            request.ContentLength = data.Length;
            Stream writer = request.GetRequestStream();
            writer.Write(data, 0, data.Length);
            writer.Close();
        }
        /// <summary>
        /// 编码方式
        /// </summary>
        /// <param name="Pars"></param>
        /// <returns></returns>
        private static byte[] EncodePars(NameValueCollection Pars)
        {
            return Encoding.UTF8.GetBytes(ParsToString(Pars));
        }
        /// <summary>
        /// 参数转为字符串
        /// </summary>
        /// <param name="Pars"></param>
        /// <returns></returns>
        private static String ParsToString(NameValueCollection Pars)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string k in Pars.Keys)
            {
                if (sb.Length > 0)
                {
                    sb.Append("&");
                }
                sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString()));
            }
            return sb.ToString();
        }
        #endregion



        /// <summary>
        /// 开放平台签名[MD5 + BASE64]
        /// </summary>
        /// <param name="encryptStr">加密的字符串(请求数据[data] + 消息密钥[key])</param>
        /// <param name="charset">编码方式, 默认UTF-8</param>
        /// <returns></returns>
        public static string EncryptMD5Base64(string encryptStr, string charset = "UTF-8")
        {
            string rValue = "";
            var m5 = new MD5CryptoServiceProvider();

            byte[] inputBye;
            byte[] outputBye;
            try
            {
                inputBye = Encoding.GetEncoding(charset).GetBytes(encryptStr);
            }
            catch (Exception)
            {
                inputBye = Encoding.UTF8.GetBytes(encryptStr);
            }
            outputBye = m5.ComputeHash(inputBye);
            rValue = Convert.ToBase64String(outputBye, 0, outputBye.Length);

            return rValue;
        }
    }
}

results matching ""

    No results matching ""