您的位置:首页 > 理论基础 > 计算机网络

C# http 发送接收xml数据

2015-02-05 22:26 399 查看
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 id="..." which we need to get rid of

re = new Regex("<title(http://www.cnblogs.com/shuzhengyi/admin/file://s+id/=.+?)>", 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;

}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: