C# WebRequest WebClient Post请求 无乱码
2009-08-10 09:55 闫妍 阅读(281) 评论(0) 编辑 收藏 举报Web.Config
<globalization responseEncoding="gb2312"/>
CS文件
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Net; using System.Text; using System.IO; using System.Xml; using System.Collections; using System.Diagnostics; namespace WebPortal { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { CoreProxy.Class1 c = new CoreProxy.Class1(); c.test1(); } protected void Button2_Click(object sender, EventArgs e) { webquerst1(); } public void webquers2() { string html = null; string url = "http://china.alibaba.com/keyword/promotion.htm?catId=14"; WebRequest req = WebRequest.Create(url); req.Method = "POST"; WebResponse res = req.GetResponse(); Stream receiveStream = res.GetResponseStream(); Encoding encode = Encoding.GetEncoding("gb2312"); StreamReader sr = new StreamReader(receiveStream, encode); char[] readbuffer = new char[256]; int n = sr.Read(readbuffer, 0, 256); while (n > 0) { string str = new string(readbuffer, 0, n); html += str; n = sr.Read(readbuffer, 0, 256); } System.Console.Write(html); } //成功!,利用WebRequest 一次Post提交XML内容 public void webquerst1() { WebRequest request = WebRequest.Create("http://192.168.1.244/WebPortal/PortalHandler.ashx"); // Set the Method property of the request to POST. request.Method = "POST"; // Create POST data and convert it to a byte array. System.Xml.XmlDocument xmlpostdata = new System.Xml.XmlDocument(); xmlpostdata.Load(Server.MapPath("XML/20097.xml")); string postData = HttpUtility.HtmlEncode(xmlpostdata.InnerXml); //普通字符串内容 //string postData = "你好,1232355 abdcde"; byte[] byteArray = Encoding.UTF8.GetBytes(postData); // Set the ContentType property of the WebRequest. request.ContentType = "application/x-www-form-urlencoded"; // Set the ContentLength property of the WebRequest. request.ContentLength = byteArray.Length; // Get the request stream. Stream dataStream = request.GetRequestStream(); // Write the data to the request stream. dataStream.Write(byteArray, 0, byteArray.Length); // Close the Stream object. dataStream.Close(); // Get the response. WebResponse response = request.GetResponse(); // Display the status. //Console.WriteLine(((HttpWebResponse)response).StatusDescription); // Get the stream containing content returned by the server. dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream); // Read the content. string responseFromServer = reader.ReadToEnd(); // Display the content. //Console.WriteLine(responseFromServer); // Clean up the streams. reader.Close(); dataStream.Close(); response.Close(); } protected void Button3_Click(object sender, EventArgs e) { WebClientPost(); } //重点!! 成功 利用Webclient Post 按字段的方式提交每个字段的内容给服务器端 public void WebClientPost() { System.Xml.XmlDocument xmlpostdata = new System.Xml.XmlDocument(); xmlpostdata.Load(Server.MapPath("XML/OrderClient.xml")); string OrderClient = HttpUtility.HtmlEncode(xmlpostdata.InnerXml); xmlpostdata.Load(Server.MapPath("XML/Order.xml")); string Order = HttpUtility.HtmlEncode(xmlpostdata.InnerXml); xmlpostdata.Load(Server.MapPath("XML/TargetOut.xml")); string TargetOut = HttpUtility.HtmlEncode(xmlpostdata.InnerXml); xmlpostdata.Load(Server.MapPath("XML/ArrayOfOrderDetail.xml")); string ArrayOfOrderDetail = HttpUtility.HtmlEncode(xmlpostdata.InnerXml); System.Net.WebClient WebClientObj = new System.Net.WebClient(); System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection(); //添加值域 PostVars.Add("OrderClient", OrderClient); PostVars.Add("Order", Order); PostVars.Add("TargetOut", TargetOut); PostVars.Add("ArrayOfOrderDetail", ArrayOfOrderDetail); try { byte[] byRemoteInfo = WebClientObj.UploadValues("http://192.168.1.244/WebPortal/PlaceOrder.ashx", "POST", PostVars); //下面都没用啦,就上面一句话就可以了 string sRemoteInfo = System.Text.Encoding.Default.GetString(byRemoteInfo); //这是获取返回信息 Debug.WriteLine(sRemoteInfo); } catch { } } //未测试,使用WebClient 一次性提交POst public static string SendPostRequest(string url, string postString) { byte[] postData = Encoding.UTF8.GetBytes(postString); WebClient client = new WebClient(); client.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); client.Headers.Add("ContentLength", postData.Length.ToString()); byte[] responseData = client.UploadData(url, "POST", postData); return Encoding.Default.GetString(responseData); } /// <summary> /// 这个是用WEbRequest 提交到WEbService 的例子 /// </summary> /// <param name="URL"></param> /// <param name="MethodName"></param> /// <param name="Pars"></param> /// <returns></returns> public static XmlDocument QueryPostWebService(String URL, String MethodName, Hashtable Pars) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; SetWebRequest(request); byte[] data = EncodePars(Pars); WriteRequestData(request, data); return ReadXmlResponse(request.GetResponse()); } private static void SetWebRequest(HttpWebRequest request) { request.Credentials = CredentialCache.DefaultCredentials; request.Timeout = 10000; } private static void WriteRequestData(HttpWebRequest request, byte[] data) { request.ContentLength = data.Length; Stream writer = request.GetRequestStream(); writer.Write(data, 0, data.Length); writer.Close(); } private static byte[] EncodePars(Hashtable Pars) { return Encoding.UTF8.GetBytes(ParsToString(Pars)); } private static String ParsToString(Hashtable 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(); } private static XmlDocument ReadXmlResponse(WebResponse response) { StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); String retXml = sr.ReadToEnd(); sr.Close(); XmlDocument doc = new XmlDocument(); doc.LoadXml(retXml); return doc; } private static void AddDelaration(XmlDocument doc) { XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.InsertBefore(decl, doc.DocumentElement); } protected void Button4_Click(object sender, EventArgs e) { } } }
ashx
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Diagnostics; using System.IO; using System.Xml; namespace WebPortal { /// <summary> /// $codebehindclassname$ 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class PortalHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { string testGet = context.Request["testGet"]; string testPost = context.Request["testPost"]; Debug.WriteLine(testGet); Debug.WriteLine(testPost); //一次性提交的方式 //获得内容长度 int len = context.Request.ContentLength; //获得所有内容流 StreamReader reader = new StreamReader(context.Request.InputStream); //读取内容 string responseFromServer = reader.ReadToEnd(); //字段提交Post方式 string a1 = context.Request["A1"]; string a2 = context.Request["A2"]; string a3 = context.Request["A3"]; //解析Html编码 string re = HttpUtility.HtmlDecode(a1); XmlDocument xd = new XmlDocument(); //加载XML xd.LoadXml(re); context.Response.ContentType = "text/plain"; context.Response.Write(testGet); } public bool IsReusable { get { return false; } } } }