项目中用到了…在网上找到了一个,整理了一下,发出来
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | /* * By: 落落 * URL: Www.MyLuoLuo.Com */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; using System.Web; namespace NetXenClient.Tools { /// <summary> /// 向指定URL发送Post信息的帮助类 /// </summary> public class WebPostHelp { /// <summary> /// 请求URL /// </summary> string url; /// <summary> /// 编码方式 /// </summary> Encoding dataEncoding; /// <summary> /// 超时时间 /// </summary> int timeout; /// <summary> /// 构造函数 /// </summary> /// <param name="url">需要要提交数据的URL</param> /// <param name="dataEncoding">编码方式</param> /// <param name="timeout">超时时间</param> public WebPostHelp( string url,Encoding dataEncoding, int timeout) { this .url = url; this .dataEncoding = dataEncoding; this .timeout = timeout; } /// <summary> /// Post数据 /// </summary> /// <param name="postData">Post参数集合</param> /// <param name="cookies">用来接收Cookie信息</param> /// <returns></returns> public string Post(Dictionary< string , string > postData, ref CookieContainer cookies) { //创建对象 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); //设置提交方式 webRequest.Method = "POST" ; //是否保持连接 webRequest.KeepAlive = true ; // Content-TypeHTTP标头 webRequest.ContentType = "application/x-www-form-urlencoded" ; //RefererHTTP 标头 webRequest.Referer = url.Remove(url.LastIndexOf( "/" )); //设置连接超时的时间 webRequest.Timeout = timeout; //设置Cookie容器 if (cookies == null ) { cookies = new CookieContainer(); } webRequest.CookieContainer = cookies; if (postData != null && postData.Count > 0) { StringBuilder newStringBuilder = new StringBuilder(); //转换Data数据 foreach (KeyValuePair< string , string > kvp in postData) { newStringBuilder.Append(HttpUtility.UrlEncode(kvp.Key)); newStringBuilder.Append( "=" ); newStringBuilder.Append(HttpUtility.UrlEncode(kvp.Value)); newStringBuilder.Append( "&" ); } //转换数据 byte [] byteData = this .dataEncoding.GetBytes(newStringBuilder.ToString().TrimEnd( '&' )); //设置数据长度 webRequest.ContentLength = byteData.Length; using (Stream reqStream = webRequest.GetRequestStream()) { //写入 reqStream.Write(byteData, 0, byteData.Length); } } //用来接收返回的数据 string ret = String.Empty; using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse()) { cookies = webRequest.CookieContainer; using (Stream resStream = webResponse.GetResponseStream()) { using (StreamReader sr = new StreamReader(resStream, this .dataEncoding)) { //读取返回 数据 ret = sr.ReadToEnd(); } } } return ret; } } } |
完整代码如上