• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#http发送接收xml数据

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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

namespace TaoBaoInterface
{
    public class Service
    {
        public static string TaobaoUrl = "http://110.75.50.103/user/WareHouseReceiveMessage.do";

        /***
        *   测试DSA公钥
        */
       static String strPublicKey = "MIIBtjCCASsGByqGSM44BAEwggEeAoGBAKRQ3ELATnIGJbRJE9+84RER2ULkU7eS"
                        + "zrvX7RF1El0zlv65yI4Qgt9LeU464F6tV42aogHvh5lIe5HoKv0hKM+Am5BgSOSz"
                        + "5f1+SD3NXOaiQfTcSZCOtZhbcZlPDx7OYraISenxHmEAUZoli0n9IscmsCprIJI0"
                        + "/o1A9cnyQWoRAhUApBkCOX0pRTaE6P5s0VjgWW43hnkCgYAOG949Z9DcaRPuyCq0"
                        + "fN7/5IVgIPsqA0vCY0ZWe+PULdfvKg+fLERt2LMYJlksD/KUb4FLgdKtBqI1ggbZ"
                        + "Jdc8lbvgIFzV1XnYkcMJIVobSIAZDVA+2F/uVhj17EiOGWw1Oa+cRP8rDFNkUh2V"
                        + "XNDqncfQr5zA1W/dQg4wu2zb2gOBhAACgYBCvUMmkn8wAliTXcFDn0/ZvO/2J9iO"
                        + "l8FxsyhQu9iiF1OCvmTkT5Rwb3z61hixxi5JO4+aqZszlm8wMkxqOS8IaDYIWQl6"
                        + "/rLV2+9YENEhmIuC3ngce3gZIsayzdxDnzxUqTww8MEV+t3SmWxgLHbTpvXhyFG6"
                        + "DjzLcWRlT6RNtA==";

 

        /***
           测试DSA私钥
        */
       static String strPrivateKey = "MIIBSgIBADCCASsGByqGSM44BAEwggEeAoGBAKRQ3ELATnIGJbRJE9+84RER2ULk"
                        + "U7eSzrvX7RF1El0zlv65yI4Qgt9LeU464F6tV42aogHvh5lIe5HoKv0hKM+Am5Bg"
                        + "SOSz5f1+SD3NXOaiQfTcSZCOtZhbcZlPDx7OYraISenxHmEAUZoli0n9IscmsCpr"
                        + "IJI0/o1A9cnyQWoRAhUApBkCOX0pRTaE6P5s0VjgWW43hnkCgYAOG949Z9DcaRPu"
                        + "yCq0fN7/5IVgIPsqA0vCY0ZWe+PULdfvKg+fLERt2LMYJlksD/KUb4FLgdKtBqI1"
                        + "ggbZJdc8lbvgIFzV1XnYkcMJIVobSIAZDVA+2F/uVhj17EiOGWw1Oa+cRP8rDFNk"
                        + "Uh2VXNDqncfQr5zA1W/dQg4wu2zb2gQWAhRGDs9OGMdl9f4Sx/fzUSszlYCm1g==";
       
        /// <summary>
        ///
        /// </summary>
        /// <param name="url">请求的url地地址</param>
        /// <param name="xml">请求的xml内容</param>
        /// <returns></returns>
        public static string SendAPI(string url,string xml)
        {
            /***
            *   测试DSA公钥
            */
          
            #region 对xml做DSA密钥签名           
            #endregion           
            string formatString = "logistics_interface={0}&data_digest={1}&type=v1.0";
            string postData = string.Format(formatString, HttpUtility.UrlEncode(xml, Encoding.GetEncoding("GBK")), HttpUtility.UrlEncode(DSAEnCryptoService(xml), Encoding.GetEncoding("GBK")));
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(postData);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "Post";
            request.ContentType = "application/x-www-form-urlencoded; charset=GBK";
            request.ContentLength = data.Length;

            //发送数据
            Stream newStream = request.GetRequestStream();
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            HttpWebResponse responseSorce = (HttpWebResponse)request.GetResponse();

            Stream stream = responseSorce.GetResponseStream();
            StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("GBK"));
            string content = reader.ReadToEnd();
            content = Filert(content);
            stream.Close();
            return content;          
        }

        public static string DecodeReponse(string content)
        {

            int start = content.IndexOf("<?xml");
            int end = content.LastIndexOf("</Response>");
            int length = end - start + "</Response>".Length;
            string res =  content.Substring(start, length);
            return res;
        }

        #region Dirty work
        private static string Filert(string responseHtml)
        {
           
            // ---------------------------------
            // Wait for the closing </html> tag
            // ---------------------------------
            Regex eof = new Regex("</html>", RegexOptions.IgnoreCase);


            string finalHtml = responseHtml.ToString();
            Regex re = null;


            // The title has an , RegexOptions.IgnoreCase);
            finalHtml = re.Replace(finalHtml, new MatchEvaluator(TitleMatch));

            // Replace language="javascript" with script type="text/javascript"
            re = new Regex("(?<=script\\s*)(language=\"javascript\")", RegexOptions.IgnoreCase);
            finalHtml = re.Replace(finalHtml, new MatchEvaluator(JavaScriptMatch));

            // If there are still any language="javascript" are left, delete them
            finalHtml = Regex.Replace(finalHtml, "language=\"javascript\"", string.Empty, RegexOptions.IgnoreCase);

            // Clean up images. Some images have a border property which is deprecated in XHTML
            re = new Regex("<img.*(border=\".*?\").*?>", RegexOptions.IgnoreCase);
            finalHtml = re.Replace(finalHtml, new MatchEvaluator(ImageBorderMatch));

            // Wrap the __VIEWSTATE tag in a div to pass validation
            re = new Regex("(<input.*?__VIEWSTATE.*?/>)", RegexOptions.IgnoreCase);
            finalHtml = re.Replace(finalHtml, new MatchEvaluator(ViewStateMatch));

            // If __doPostBack is registered, replace the whole function
            if (finalHtml.IndexOf("__doPostBack") > -1)
            {
                try
                {
                    int pos1 = finalHtml.IndexOf("var theform;");
                    int pos2 = finalHtml.IndexOf("theform.__EVENTTARGET", pos1);
                    string methodText = finalHtml.Substring(pos1, pos2 - pos1);
                    string formID = Regex.Match(methodText, "document.forms\\[\"(.*?)\"\\];", RegexOptions.IgnoreCase).Groups[1].Value.Replace(":", "_");

                    finalHtml = finalHtml.Replace(methodText,
                        @"var theform = document.getElementById ('" + formID + "');\r\n\t\t");
                }
                catch
                {
                }
            }

            // Remove the "name" attribute from <form> tags because they are invalid
            re = new Regex("<form\\s+(name=.*?\\s)", RegexOptions.IgnoreCase);
            finalHtml = re.Replace(finalHtml, new MatchEvaluator(FormNameMatch));
            //return finalHtml;

            // Write the formatted HTML back
            byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(finalHtml);
            return System.Text.Encoding.Default.GetString(data);
        }

        //---------------------------------------------------------------------------
        private static string TitleMatch(Match m)
        {
            return m.ToString().Replace(m.Groups[1].Value, string.Empty);
        }

        //---------------------------------------------------------------------------
        private static string JavaScriptMatch(Match m)
        {
            return m.ToString().Replace(m.Groups[1].Value, "type=\"text/javascript\"");
        }

        //---------------------------------------------------------------------------
        private static string ImageBorderMatch(Match m)
        {
            return m.ToString().Replace(m.Groups[1].Value, string.Empty);
        }

        //---------------------------------------------------------------------------
        private static string ViewStateMatch(Match m)
        {
            return string.Concat("<div>", m.Groups[1].Value, "</div>");
        }

        //---------------------------------------------------------------------------
        private static string FormNameMatch(Match m)
        {
            return m.ToString().Replace(m.Groups[1].Value, string.Empty);
        }
        #endregion

        /// <summary>
        /// 用私钥加密数据
        /// </summary>
        /// <param name="str"></param>
        /// <returns>返回的是签名数据</returns>
        public static string DSAEnCryptoService(string str)
        {
            DSACryptoServiceProvider dsac = new DSACryptoServiceProvider();
            byte[] privateBytes = null;
            byte[] bytes = Encoding.Default.GetBytes(str); //xml数据

            privateBytes = Convert.FromBase64String(strPrivateKey);

            AsnKeyParser keyParser = new AsnKeyParser(privateBytes);

            dsac.ImportParameters(keyParser.ParseDSAPrivateKey());

            byte[] sign = dsac.SignData(bytes);

            string yy = "";
            foreach (byte bt in sign)
            {

                yy += bt.ToString() + ", ";
            }
            string dd = yy;

            string strsign = Convert.ToBase64String(sign);
            return strsign;

        }


        /// <summary>
        /// 用公钥解密数据
        /// </summary>
        /// <param name="str"></param>
        /// <returns>返回的是签名数据</returns>
        public static bool DSACryptoService(string str, string signstr)
        {
            try
            {
                byte[] bytes = Encoding.Default.GetBytes(str); //xml数据(URL解码以后的)
                byte[] signbytes = Convert.FromBase64String(signstr);  //签名后的数据
                DSACryptoServiceProvider dsac2 = new DSACryptoServiceProvider();
                byte[] publicBytes = null;
                publicBytes = Convert.FromBase64String(strPublicKey);
                AsnKeyParser keyParser1 = new AsnKeyParser(publicBytes);
                dsac2.ImportParameters(keyParser1.ParseDSAPublicKey());
                bool ver = dsac2.VerifyData(bytes, signbytes);
                if (ver)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception e)
            {
                string strlog = str + "| " + signstr + "| " + e.ToString();
                return false;
            }
        }
    }
}


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#winform登陆成功打开主form,同时关闭登陆form发布时间:2022-07-13
下一篇:
C#调用AForge类库操作摄像头发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap