HttpWebRequest和HttpWebResponse類是用於發送和接收HTTP數據的最好選擇。它們支持一系列有用的屬性。這兩個類位 於System.Net命名空間,默認狀況下這個類對於控制檯程序來講是可訪問的。請注意,HttpWebRequest對象不是利用new關鍵字經過構 造函數來建立的,而是利用工廠機制(factory mechanism)經過Create()方法來建立的。另外,你可能預計須要顯式地調用一個「Send」方法,實際上不須要。接下來調用 HttpWebRequest.GetResponse()方法返回的是一個HttpWebResponse對象。你能夠把HTTP響應的數據流 (stream)綁定到一個StreamReader對象,而後就能夠經過ReadToEnd()方法把整個HTTP響應做爲一個字符串取回。也能夠經過 StreamReader.ReadLine()方法逐行取回HTTP響應的內容。html
這種技術展現瞭如何限制請求重定向(request redirections)的次數, 而且設置了一個超時限制。下面是HttpWebRequest的一些屬性,這些屬性對於輕量級的自動化測試程序是很是重要的。node
l AllowAutoRedirect:獲取或設置一個值,該值指示請求是否應跟隨重定向響應。web
l CookieContainer:獲取或設置與此請求關聯的cookie。json
l Credentials:獲取或設置請求的身份驗證信息。api
l KeepAlive:獲取或設置一個值,該值指示是否與 Internet 資源創建持久性鏈接。瀏覽器
l MaximumAutomaticRedirections:獲取或設置請求將跟隨的重定向的最大數目。緩存
l Proxy:獲取或設置請求的代理信息。服務器
l SendChunked:獲取或設置一個值,該值指示是否將數據分段發送到 Internet 資源。cookie
l Timeout:獲取或設置請求的超時值。網絡
l UserAgent:獲取或設置 User-agent HTTP 標頭的值
C# HttpWebRequest提交數據方式其實就是GET和POST兩種,那麼具體的實現以及操做注意事項是什麼呢?那麼本文就向你詳細介紹C# HttpWebRequest提交數據方式的這兩種利器。
C# HttpWebRequest提交數據方式學習以前咱們先來看看什麼是HttpWebRequest,它是 .net 基類庫中的一個類,在命名空間 System.Net 下面,用來使用戶經過HTTP協議和服務器交互。
C# HttpWebRequest的做用:
HttpWebRequest對HTTP協議進行了完整的封裝,對HTTP協議中的 Header, Content, Cookie 都作了屬性和方法的支持,很容易就能編寫出一個模擬瀏覽器自動登陸的程序。
C# HttpWebRequest提交數據方式:
程序使用HTTP協議和服務器交互主要是進行數據的提交,一般數據的提交是經過 GET 和 POST 兩種方式來完成,下面對這兩種方式進行一下說明:
C# HttpWebRequest提交數據方式1. GET 方式。
GET 方式經過在網絡地址附加參數來完成數據的提交,好比在地址 http://www.google.com/webhp?hl=zh-CN 中,前面部分 http://www.google.com/webhp 表示數據提交的網址,後面部分 hl=zh-CN 表示附加的參數,其中 hl 表示一個鍵(key), zh-CN 表示這個鍵對應的值(value)。程序代碼以下:
HttpWebRequest req =
(HttpWebRequest) HttpWebRequest.Create(
"http://www.google.com/webhp?hl=zh-CN" );
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{
//在這裏對接收到的頁面內容進行處理
}
C# HttpWebRequest提交數據方式2. POST 方式。
POST 方式經過在頁面內容中填寫參數的方法來完成數據的提交,參數的格式和 GET 方式同樣,是相似於 hl=zh-CN&newwindow=1 這樣的結構。程序代碼以下:
string param = "hl=zh-CN&newwindow=1"; //參數
byte[] bs = Encoding.ASCII.GetBytes(param); //參數轉化爲ascii碼
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.google.com/intl/zh-CN/" ); //建立request
req.Method = "POST"; //肯定傳值的方式,此處爲post方式傳值
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = bs.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse wr = req.GetResponse())
{
//在這裏對接收到的頁面內容進行處理
}
在上面的代碼中,咱們訪問了 www.google.com 的網址,分別以 GET 和 POST 方式提交了數據,並接收了返回的頁面內容。然而,若是提交的參數中含有中文,那麼這樣的處理是不夠的,須要對其進行編碼,讓對方網站可以識別。
C# HttpWebRequest提交數據方式3. 使用 GET 方式提交中文數據。
GET 方式經過在網絡地址中附加參數來完成數據提交,對於中文的編碼,經常使用的有 gb2312 和 utf8 兩種,用 gb2312 方式編碼訪問的程序代碼以下:
Encoding myEncoding = Encoding.GetEncoding("gb2312"); //肯定用哪一種中文編碼方式
string address = "http://www.baidu.com/s?" + HttpUtility.UrlEncode("參數一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding); //拼接數據提交的網址和通過中文編碼後的中文參數
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address); //建立request
req.Method = "GET"; //肯定傳值方式,此處爲get方式
using (WebResponse wr = req.GetResponse())
{
//在這裏對接收到的頁面內容進行處理
}
在上面的程序代碼中,咱們以 GET 方式訪問了網址 http://www.baidu.com/s ,傳遞了參數「參數一=值一」,因爲沒法告知對方提交數據的編碼類型,因此編碼方式要以對方的網站爲標準。常見的網站中, www.baidu.com (百度)的編碼方式是 gb2312, www.google.com (谷歌)的編碼方式是 utf8。
C# HttpWebRequest提交數據方式4. 使用 POST 方式提交中文數據。
POST 方式經過在頁面內容中填寫參數的方法來完成數據的提交,因爲提交的參數中能夠說明使用的編碼方式,因此理論上能得到更大的兼容性。用 gb2312 方式編碼訪問的程序代碼以下:
Encoding myEncoding = Encoding.GetEncoding("gb2312"); //肯定中文編碼方式。此處用gb2312
string param = HttpUtility.UrlEncode("參數一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding) + "&" + HttpUtility.UrlEncode("參數二", myEncoding) + "=" + HttpUtility.UrlEncode("值二", myEncoding);
byte[] postBytes = Encoding.ASCII.GetBytes(param); //將參數轉化爲assic碼
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.baidu.com/s" );
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded;charset=gb2312";
req.ContentLength = postBytes.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse wr = req.GetResponse())
{
//在這裏對接收到的頁面內容進行處理
}
從上面的代碼能夠看出, POST 中文數據的時候,先使用 UrlEncode 方法將中文字符轉換爲編碼後的 ASCII 碼,而後提交到服務器,提交的時候能夠說明編碼的方式,用來使對方服務器可以正確的解析。
以上列出了客戶端程序使用HTTP協議與服務器交互的狀況,經常使用的是 GET 和 POST 方式。如今流行的 WebService 也是經過 HTTP 協議來交互的,使用的是 POST 方法。與以上稍有所不一樣的是, WebService 提交的數據內容和接收到的數據內容都是使用了 XML 方式編碼。因此, HttpWebRequest 也可使用在調用 WebService 的狀況下。
1 #region 公共方法 2 /// <summary> 3 /// Get數據接口 4 /// </summary> 5 /// <param name="getUrl">接口地址</param> 6 /// <returns></returns> 7 private static string GetWebRequest(string getUrl) 8 { 9 string responseContent = ""; 10 11 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(getUrl); 12 request.ContentType = "application/json"; 13 request.Method = "GET"; 14 15 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 16 //在這裏對接收到的頁面內容進行處理 17 using (Stream resStream = response.GetResponseStream()) 18 { 19 using (StreamReader reader = new StreamReader(resStream, Encoding.UTF8)) 20 { 21 responseContent = reader.ReadToEnd().ToString(); 22 } 23 } 24 return responseContent; 25 } 26 /// <summary> 27 /// Post數據接口 28 /// </summary> 29 /// <param name="postUrl">接口地址</param> 30 /// <param name="paramData">提交json數據</param> 31 /// <param name="dataEncode">編碼方式(Encoding.UTF8)</param> 32 /// <returns></returns> 33 private static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode) 34 { 35 string responseContent = string.Empty; 36 try 37 { 38 byte[] byteArray = dataEncode.GetBytes(paramData); //轉化 39 HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl)); 40 webReq.Method = "POST"; 41 webReq.ContentType = "application/x-www-form-urlencoded"; 42 webReq.ContentLength = byteArray.Length; 43 using (Stream reqStream = webReq.GetRequestStream()) 44 { 45 reqStream.Write(byteArray, 0, byteArray.Length);//寫入參數 46 //reqStream.Close(); 47 } 48 using (HttpWebResponse response = (HttpWebResponse)webReq.GetResponse()) 49 { 50 //在這裏對接收到的頁面內容進行處理 51 using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default)) 52 { 53 responseContent = sr.ReadToEnd().ToString(); 54 } 55 } 56 } 57 catch (Exception ex) 58 { 59 return ex.Message; 60 } 61 return responseContent; 62 } 63 64 #endregion
post支持cookie
1 /// <summary> 2 /// 發起Post請求(採用HttpWebRequest,支持傳Cookie) 3 /// </summary> 4 /// <param name="strUrl">請求Url</param> 5 /// <param name="formData">發送的表單數據</param> 6 /// <param name="strResult">返回請求結果(若是請求失敗,返回異常消息)</param> 7 /// <param name="cookieContainer">隨同HTTP請求發送的Cookie信息,若是不須要身份驗證能夠爲空</param> 8 /// <returns>返回:是否請求成功</returns> 9 public static bool HttpPost(string strUrl, Dictionary<string, string> formData, CookieContainer cookieContainer, out string strResult) 10 { 11 string strPostData = null; 12 if (formData != null && formData.Count > 0) 13 { 14 StringBuilder sbData = new StringBuilder(); 15 int i = 0; 16 foreach (KeyValuePair<string, string> data in formData) 17 { 18 if (i > 0) 19 { 20 sbData.Append("&"); 21 } 22 sbData.AppendFormat("{0}={1}", data.Key, data.Value); 23 i++; 24 } 25 strPostData = sbData.ToString(); 26 } 27 28 byte[] postBytes = string.IsNullOrEmpty(strPostData) ? new byte[0] : Encoding.UTF8.GetBytes(strPostData); 29 30 return HttpPost(strUrl, postBytes, cookieContainer, out strResult); 31 }
post上傳文件
1 /// <summary> 2 /// 發起Post文件請求(採用HttpWebRequest,支持傳Cookie) 3 /// </summary> 4 /// <param name="strUrl">請求Url</param> 5 /// <param name="strFilePostName">上傳文件的PostName</param> 6 /// <param name="strFilePath">上傳文件路徑</param> 7 /// <param name="cookieContainer">隨同HTTP請求發送的Cookie信息,若是不須要身份驗證能夠爲空</param> 8 /// <param name="strResult">返回請求結果(若是請求失敗,返回異常消息)</param> 9 /// <returns>返回:是否請求成功</returns> 10 public static bool HttpPostFile(string strUrl, string strFilePostName, string strFilePath, CookieContainer cookieContainer, out string strResult) 11 { 12 HttpWebRequest request = null; 13 FileStream fileStream = FileHelper.GetFileStream(strFilePath); 14 15 try 16 { 17 if (fileStream == null) 18 { 19 throw new FileNotFoundException(); 20 } 21 22 request = (HttpWebRequest)WebRequest.Create(strUrl); 23 request.Method = "POST"; 24 request.KeepAlive = false; 25 request.Timeout = 30000; 26 27 if (cookieContainer != null) 28 { 29 request.CookieContainer = cookieContainer; 30 } 31 32 string boundary = string.Format("---------------------------{0}", DateTime.Now.Ticks.ToString("x")); 33 34 byte[] header = Encoding.UTF8.GetBytes(string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: application/octet-stream\r\n\r\n", 35 boundary, strFilePostName, Path.GetFileName(strFilePath))); 36 byte[] footer = Encoding.UTF8.GetBytes(string.Format("\r\n--{0}--\r\n", boundary)); 37 38 request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary); 39 request.ContentLength = header.Length + fileStream.Length + footer.Length; 40 41 using (Stream reqStream = request.GetRequestStream()) 42 { 43 // 寫入分割線及數據信息 44 reqStream.Write(header, 0, header.Length); 45 46 // 寫入文件 47 FileHelper.WriteFile(reqStream, fileStream); 48 49 // 寫入尾部 50 reqStream.Write(footer, 0, footer.Length); 51 } 52 53 strResult = GetResponseResult(request, cookieContainer); 54 } 55 catch (Exception ex) 56 { 57 strResult = ex.Message; 58 return false; 59 } 60 finally 61 { 62 if (request != null) 63 { 64 request.Abort(); 65 } 66 if (fileStream != null) 67 { 68 fileStream.Close(); 69 } 70 } 71 72 return true; 73 } 74 75 76 /// <summary> 77 /// 獲取請求結果字符串 78 /// </summary> 79 /// <param name="request">請求對象(發起請求以後)</param> 80 /// <param name="cookieContainer">隨同HTTP請求發送的Cookie信息,若是不須要身份驗證能夠爲空</param> 81 /// <returns>返回請求結果字符串</returns> 82 private static string GetResponseResult(HttpWebRequest request, CookieContainer cookieContainer = null) 83 { 84 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 85 { 86 if (cookieContainer != null) 87 { 88 response.Cookies = cookieContainer.GetCookies(response.ResponseUri); 89 } 90 using (Stream rspStream = response.GetResponseStream()) 91 { 92 using (StreamReader reader = new StreamReader(rspStream, Encoding.UTF8)) 93 { 94 return reader.ReadToEnd(); 95 } 96 } 97 } 98 }
OAuth頭部
1 //構造OAuth頭部 2 StringBuilder oauthHeader = new StringBuilder(); 3 oauthHeader.AppendFormat("OAuth realm=\"\", oauth_consumer_key={0}, ", apiKey); 4 oauthHeader.AppendFormat("oauth_nonce={0}, ", nonce); 5 oauthHeader.AppendFormat("oauth_timestamp={0}, ", timeStamp); 6 oauthHeader.AppendFormat("oauth_signature_method={0}, ", "HMAC-SHA1"); 7 oauthHeader.AppendFormat("oauth_version={0}, ", "1.0"); 8 oauthHeader.AppendFormat("oauth_signature={0}, ", sig); 9 oauthHeader.AppendFormat("oauth_token={0}", accessToken); 10 11 //構造請求 12 StringBuilder requestBody = new StringBuilder(""); 13 Encoding encoding = Encoding.GetEncoding("utf-8"); 14 byte[] data = encoding.GetBytes(requestBody.ToString()); 15 16 // Http Request的設置 17 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); 18 request.Headers.Set("Authorization", oauthHeader.ToString()); 19 //request.Headers.Add("Authorization", authorization); 20 request.ContentType = "application/atom+xml"; 21 request.Method = "GET";
http://www.javashuo.com/article/p-vzdmbjve-dp.html
1 1.POST方法(httpWebRequest) 2 3 4 5 6 7 //body是要傳遞的參數,格式"roleId=1&uid=2" 8 //post的cotentType填寫:"application/x-www-form-urlencoded" 9 //soap填寫:"text/xml; charset=utf-8" 10 public static string PostHttp(string url, string body, string contentType) 11 { 12 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); 13 14 httpWebRequest.ContentType = contentType; 15 httpWebRequest.Method = "POST"; 16 httpWebRequest.Timeout = 20000; 17 18 byte[] btBodys = Encoding.UTF8.GetBytes(body); 19 httpWebRequest.ContentLength = btBodys.Length; 20 httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length); 21 22 HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); 23 StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()); 24 string responseContent = streamReader.ReadToEnd(); 25 26 httpWebResponse.Close(); 27 streamReader.Close(); 28 httpWebRequest.Abort(); 29 httpWebResponse.Close(); 30 31 return responseContent; 32 } 33 34 POST方法(httpWebRequest) 35 36 37 2.POST方法(WebClient) 38 39 40 41 /// <summary> 42 /// 經過WebClient類Post數據到遠程地址,須要Basic認證; 43 /// 調用端本身處理異常 44 /// </summary> 45 /// <param name="uri"></param> 46 /// <param name="paramStr">name=張三&age=20</param> 47 /// <param name="encoding">請先確認目標網頁的編碼方式</param> 48 /// <param name="username"></param> 49 /// <param name="password"></param> 50 /// <returns></returns> 51 public static string Request_WebClient(string uri, string paramStr, Encoding encoding, string username, string password) 52 { 53 if (encoding == null) 54 encoding = Encoding.UTF8; 55 56 string result = string.Empty; 57 58 WebClient wc = new WebClient(); 59 60 // 採起POST方式必須加的Header 61 wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); 62 63 byte[] postData = encoding.GetBytes(paramStr); 64 65 if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) 66 { 67 wc.Credentials = GetCredentialCache(uri, username, password); 68 wc.Headers.Add("Authorization", GetAuthorization(username, password)); 69 } 70 71 byte[] responseData = wc.UploadData(uri, "POST", postData); // 獲得返回字符流 72 return encoding.GetString(responseData);// 解碼 73 } 74 75 POST方法(WebClient) 76 77 3.Get方法(httpWebRequest) 78 79 80 81 public static string GetHttp(string url, HttpContext httpContext) 82 { 83 string queryString = "?"; 84 85 foreach (string key in httpContext.Request.QueryString.AllKeys) 86 { 87 queryString += key + "=" + httpContext.Request.QueryString[key] + "&"; 88 } 89 90 queryString = queryString.Substring(0, queryString.Length - 1); 91 92 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + queryString); 93 94 httpWebRequest.ContentType = "application/json"; 95 httpWebRequest.Method = "GET"; 96 httpWebRequest.Timeout = 20000; 97 98 //byte[] btBodys = Encoding.UTF8.GetBytes(body); 99 //httpWebRequest.ContentLength = btBodys.Length; 100 //httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length); 101 102 HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); 103 StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()); 104 string responseContent = streamReader.ReadToEnd(); 105 106 httpWebResponse.Close(); 107 streamReader.Close(); 108 109 return responseContent; 110 } 111 112 Get方法(HttpWebRequest) 113 114 4.basic驗證的WebRequest/WebResponse 115 116 117 118 /// <summary> 119 /// 經過 WebRequest/WebResponse 類訪問遠程地址並返回結果,須要Basic認證; 120 /// 調用端本身處理異常 121 /// </summary> 122 /// <param name="uri"></param> 123 /// <param name="timeout">訪問超時時間,單位毫秒;若是不設置超時時間,傳入0</param> 124 /// <param name="encoding">若是不知道具體的編碼,傳入null</param> 125 /// <param name="username"></param> 126 /// <param name="password"></param> 127 /// <returns></returns> 128 public static string Request_WebRequest(string uri, int timeout, Encoding encoding, string username, string password) 129 { 130 string result = string.Empty; 131 132 WebRequest request = WebRequest.Create(new Uri(uri)); 133 134 if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) 135 { 136 request.Credentials = GetCredentialCache(uri, username, password); 137 request.Headers.Add("Authorization", GetAuthorization(username, password)); 138 } 139 140 if (timeout > 0) 141 request.Timeout = timeout; 142 143 WebResponse response = request.GetResponse(); 144 Stream stream = response.GetResponseStream(); 145 StreamReader sr = encoding == null ? new StreamReader(stream) : new StreamReader(stream, encoding); 146 147 result = sr.ReadToEnd(); 148 149 sr.Close(); 150 stream.Close(); 151 152 return result; 153 } 154 155 #region # 生成 Http Basic 訪問憑證 # 156 157 private static CredentialCache GetCredentialCache(string uri, string username, string password) 158 { 159 string authorization = string.Format("{0}:{1}", username, password); 160 161 CredentialCache credCache = new CredentialCache(); 162 credCache.Add(new Uri(uri), "Basic", new NetworkCredential(username, password)); 163 164 return credCache; 165 } 166 167 private static string GetAuthorization(string username, string password) 168 { 169 string authorization = string.Format("{0}:{1}", username, password); 170 171 return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization)); 172 } 173 174 #endregion 175 176 basic驗證的WebRequest/WebResponse 177 178 179 180 C#語言寫的關於HttpWebRequest 類的使用方法 181 182 http://www.jb51.net/article/57156.htm 183 184 185 186 using System; 187 188 using System.Collections.Generic; 189 190 using System.IO; 191 192 using System.Net; 193 194 using System.Text; 195 196 namespace HttpWeb 197 198 { 199 200 /// <summary> 201 202 /// Http操做類 203 204 /// </summary> 205 206 public static class httptest 207 208 { 209 210 /// <summary> 211 212 /// 獲取網址HTML 213 214 /// </summary> 215 216 /// <param name="URL">網址 </param> 217 218 /// <returns> </returns> 219 220 public static string GetHtml(string URL) 221 222 { 223 224 WebRequest wrt; 225 226 wrt = WebRequest.Create(URL); 227 228 wrt.Credentials = CredentialCache.DefaultCredentials; 229 230 WebResponse wrp; 231 232 wrp = wrt.GetResponse(); 233 234 string reader = new StreamReader(wrp.GetResponseStream(), Encoding.GetEncoding("gb2312")).ReadToEnd(); 235 236 try 237 238 { 239 240 wrt.GetResponse().Close(); 241 242 } 243 244 catch (WebException ex) 245 246 { 247 248 throw ex; 249 250 } 251 252 return reader; 253 254 } 255 256 /// <summary> 257 258 /// 獲取網站cookie 259 260 /// </summary> 261 262 /// <param name="URL">網址 </param> 263 264 /// <param name="cookie">cookie </param> 265 266 /// <returns> </returns> 267 268 public static string GetHtml(string URL, out string cookie) 269 270 { 271 272 WebRequest wrt; 273 274 wrt = WebRequest.Create(URL); 275 276 wrt.Credentials = CredentialCache.DefaultCredentials; 277 278 WebResponse wrp; 279 280 wrp = wrt.GetResponse(); 281 string html = new StreamReader(wrp.GetResponseStream(), Encoding.GetEncoding("gb2312")).ReadToEnd(); 282 283 try 284 285 { 286 287 wrt.GetResponse().Close(); 288 289 } 290 291 catch (WebException ex) 292 293 { 294 295 throw ex; 296 297 } 298 299 cookie = wrp.Headers.Get("Set-Cookie"); 300 301 return html; 302 303 } 304 305 public static string GetHtml(string URL, string postData, string cookie, out string header, string server) 306 307 { 308 309 return GetHtml(server, URL, postData, cookie, out header); 310 311 } 312 313 public static string GetHtml(string server, string URL, string postData, string cookie, out string header) 314 315 { 316 317 byte[] byteRequest = Encoding.GetEncoding("gb2312").GetBytes(postData); 318 319 return GetHtml(server, URL, byteRequest, cookie, out header); 320 321 } 322 323 public static string GetHtml(string server, string URL, byte[] byteRequest, string cookie, out string header) 324 325 { 326 327 byte[] bytes = GetHtmlByBytes(server, URL, byteRequest, cookie, out header); 328 329 Stream getStream = new MemoryStream(bytes); 330 331 StreamReader streamReader = new StreamReader(getStream, Encoding.GetEncoding("gb2312")); 332 333 string getString = streamReader.ReadToEnd(); 334 335 streamReader.Close(); 336 337 getStream.Close(); 338 339 return getString; 340 341 } 342 343 /// <summary> 344 345 /// Post模式瀏覽 346 347 /// </summary> 348 349 /// <param name="server">服務器地址 </param> 350 351 /// <param name="URL">網址 </param> 352 353 /// <param name="byteRequest">流 </param> 354 355 /// <param name="cookie">cookie </param> 356 357 /// <param name="header">句柄 </param> 358 359 /// <returns> </returns> 360 361 public static byte[] GetHtmlByBytes(string server, string URL, byte[] byteRequest, string cookie, out string header) 362 363 { 364 365 long contentLength; 366 367 HttpWebRequest httpWebRequest; 368 369 HttpWebResponse webResponse; 370 371 Stream getStream; 372 373 httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL); 374 375 CookieContainer co = new CookieContainer(); 376 377 co.SetCookies(new Uri(server), cookie); 378 379 httpWebRequest.CookieContainer = co; 380 381 httpWebRequest.ContentType = "application/x-www-form-urlencoded"; 382 383 httpWebRequest.Accept = 384 385 "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"; 386 387 httpWebRequest.Referer = server; 388 389 httpWebRequest.UserAgent = 390 391 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)"; 392 393 httpWebRequest.Method = "Post"; 394 395 httpWebRequest.ContentLength = byteRequest.Length; 396 397 Stream stream; 398 399 stream = httpWebRequest.GetRequestStream(); 400 401 stream.Write(byteRequest, 0, byteRequest.Length); 402 403 stream.Close(); 404 405 webResponse = (HttpWebResponse)httpWebRequest.GetResponse(); 406 407 header = webResponse.Headers.ToString(); 408 409 getStream = webResponse.GetResponseStream(); 410 411 contentLength = webResponse.ContentLength; 412 413 byte[] outBytes = new byte[contentLength]; 414 415 outBytes = ReadFully(getStream); 416 417 getStream.Close(); 418 419 return outBytes; 420 421 } 422 423 public static byte[] ReadFully(Stream stream) 424 425 { 426 427 byte[] buffer = new byte[128]; 428 429 using (MemoryStream ms = new MemoryStream()) 430 431 { 432 433 while (true) 434 435 { 436 437 int read = stream.Read(buffer, 0, buffer.Length); 438 439 if (read <= 0) 440 441 return ms.ToArray(); 442 443 ms.Write(buffer, 0, read); 444 445 } 446 447 } 448 449 } 450 451 /// <summary> 452 453 /// Get模式 454 455 /// </summary> 456 457 /// <param name="URL">網址 </param> 458 459 /// <param name="cookie">cookies </param> 460 461 /// <param name="header">句柄 </param> 462 463 /// <param name="server">服務器 </param> 464 465 /// <param name="val">服務器 </param> 466 467 /// <returns> </returns> 468 469 public static string GetHtml(string URL, string cookie, out string header, string server) 470 471 { 472 473 return GetHtml(URL, cookie, out header, server, ""); 474 475 } 476 477 /// <summary> 478 479 /// Get模式瀏覽 480 481 /// </summary> 482 483 /// <param name="URL">Get網址 </param> 484 485 /// <param name="cookie">cookie </param> 486 487 /// <param name="header">句柄 </param> 488 489 /// <param name="server">服務器地址 </param> 490 491 /// <param name="val"> </param> 492 493 /// <returns> </returns> 494 495 public static string GetHtml(string URL, string cookie, out string header, string server, string val) 496 497 { 498 499 HttpWebRequest httpWebRequest; 500 501 HttpWebResponse webResponse; 502 503 Stream getStream; 504 505 StreamReader streamReader; 506 507 string getString = ""; 508 509 httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL); 510 511 httpWebRequest.Accept = "*/*"; 512 513 httpWebRequest.Referer = server; 514 515 CookieContainer co = new CookieContainer(); 516 517 co.SetCookies(new Uri(server), cookie); 518 519 httpWebRequest.CookieContainer = co; 520 521 httpWebRequest.UserAgent = 522 523 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)"; 524 525 httpWebRequest.Method = "GET"; 526 527 webResponse = (HttpWebResponse)httpWebRequest.GetResponse(); 528 529 header = webResponse.Headers.ToString(); 530 531 getStream = webResponse.GetResponseStream(); 532 533 streamReader = new StreamReader(getStream, Encoding.GetEncoding("gb2312")); 534 535 getString = streamReader.ReadToEnd(); 536 537 streamReader.Close(); 538 539 getStream.Close(); 540 541 return getString; 542 543 } 544 545 } 546 547 } 548 549 有空查看: 550 551 552 553 /// <summary> 554 /// 做用描述: WebRequest操做類 555 /// </summary> 556 public static class CallWebRequest 557 { 558 /// <summary> 559 /// 經過GET請求獲取數據 560 /// </summary> 561 /// <param name="url"></param> 562 /// <returns></returns> 563 public static string Get(string url) 564 { 565 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; 566 //每次請求繞過代理,解決第一次調用慢的問題 567 request.Proxy = null; 568 //多線程併發調用時默認2個http鏈接數限制的問題,講其設爲1000 569 ServicePoint currentServicePoint = request.ServicePoint; 570 currentServicePoint.ConnectionLimit = 1000; 571 HttpWebResponse response = request.GetResponse() as HttpWebResponse; 572 string str; 573 using (Stream responseStream = response.GetResponseStream()) 574 { 575 Encoding encode = Encoding.GetEncoding("utf-8"); 576 StreamReader reader = new StreamReader(responseStream, encode); 577 str = reader.ReadToEnd(); 578 } 579 response.Close(); 580 response = null; 581 request.Abort(); 582 request = null; 583 return str; 584 } 585 586 /// <summary> 587 /// 經過POST請求傳遞數據 588 /// </summary> 589 /// <param name="url"></param> 590 /// <param name="postData"></param> 591 /// <returns></returns> 592 public static string Post(string url, string postData) 593 { 594 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; 595 596 //將發送數據轉換爲二進制格式 597 byte[] byteArray = Encoding.UTF8.GetBytes(postData); 598 //要POST的數據大於1024字節的時候, 瀏覽器並不會直接就發起POST請求, 而是會分爲倆步: 599 //1. 發送一個請求, 包含一個Expect:100-continue, 詢問Server使用願意接受數據 600 //2. 接收到Server返回的100-continue應答之後, 才把數據POST給Server 601 //直接關閉第一步驗證 602 request.ServicePoint.Expect100Continue = false; 603 //是否使用Nagle:不使用,提升效率 604 request.ServicePoint.UseNagleAlgorithm = false; 605 //設置最大鏈接數 606 request.ServicePoint.ConnectionLimit = 65500; 607 //指定壓縮方法 608 //request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); 609 request.KeepAlive = false; 610 //request.ContentType = "application/json"; 611 request.ContentType = "application/x-www-form-urlencoded"; 612 613 request.Method = "POST"; 614 request.Timeout = 20000; 615 request.ContentLength = byteArray.Length; 616 //關閉緩存 617 request.AllowWriteStreamBuffering = false; 618 619 //每次請求繞過代理,解決第一次調用慢的問題 620 request.Proxy = null; 621 //多線程併發調用時默認2個http鏈接數限制的問題,講其設爲1000 622 ServicePoint currentServicePoint = request.ServicePoint; 623 624 Stream dataStream = request.GetRequestStream(); 625 dataStream.Write(byteArray, 0, byteArray.Length); 626 dataStream.Close(); 627 628 WebResponse response = request.GetResponse(); 629 //獲取服務器返回的數據流 630 dataStream = response.GetResponseStream(); 631 StreamReader reader = new StreamReader(dataStream); 632 string responseFromServer = reader.ReadToEnd(); 633 reader.Close(); 634 dataStream.Close(); 635 request.Abort(); 636 response.Close(); 637 reader.Dispose(); 638 dataStream.Dispose(); 639 return responseFromServer; 640 } 641 } 642 643 644 645 646 647 /// <summary> 648 /// 用於外部接口調用封裝 649 /// </summary> 650 public static class ApiInterface 651 { 652 653 /// <summary> 654 ///驗證密碼是否正確 655 /// </summary> 656 public static Api_ToConfig<object> checkPwd(int userId, string old) 657 { 658 var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/checkPwd"; 659 var data = Json.ToObject<Api_ToConfig<object>>(CallWebRequest.Post(url + "?id=" + userId, "&oldPwd=" + old)); 660 //var data = Json.ToObject<Api_ToConfig<object>>(CallWebRequest.Post(url, "{\"id\":" + userId + ",oldPwd:\"" + old + "\",newPwd:\"" + pwd + "\"}")); 661 return data; 662 } 663 664 /// <summary> 665 /// 666 /// </summary> 667 public static Api_ToConfig<object> UpdatePassword(int userId, string pwd, string old) 668 { 669 var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/updatePwd"; 670 var data = Json.ToObject<Api_ToConfig<object>>(CallWebRequest.Post(url + "?id=" + userId + "&oldPwd=" + old, "&newPwd=" + pwd)); 671 //var data = Json.ToObject<Api_ToConfig<object>>(CallWebRequest.Post(url, "{\"id\":" + userId + ",oldPwd:\"" + old + "\",newPwd:\"" + pwd + "\"}")); 672 return data; 673 } 674 675 676 677 678 private static DateTime GetTime(string timeStamp) 679 { 680 DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); 681 long lTime = long.Parse(timeStamp + "0000"); 682 TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow); 683 } 684 685 686 #region 公共方法 687 688 /// <summary> 689 /// 配置文件key 690 /// </summary> 691 /// <param name="key"></param> 692 /// <param name="isOutKey"></param> 693 /// <returns></returns> 694 public static string GetConfig(string key, bool isOutKey = false) 695 { 696 // CacheRedis.Cache.RemoveObject(RedisKey.ConfigList); 697 var data = CacheRedis.Cache.Get<Api_BaseToConfig<Api_Config>>(RedisKey.ConfigList); 698 699 // var data = new Api_BaseToConfig<Api_Config>(); 700 if (data == null) 701 { 702 string dataCenterUrl = WebConfigManager.GetAppSettings("DataCenterUrl"); 703 string configurationInfoListByFilter = WebConfigManager.GetAppSettings("ConfigurationInfoListByFilter"); 704 705 string systemCoding = WebConfigManager.GetAppSettings("SystemCoding"); 706 string nodeIdentifier = WebConfigManager.GetAppSettings("NodeIdentifier"); 707 string para = "systemIdf=" + systemCoding + "&nodeIdf=" + nodeIdentifier + ""; 708 //string para = "{\"systemIdf\":\"" + systemCoding + "\",\"nodeIdf\":\"" + nodeIdentifier + "\"}"; 709 710 string result = CallWebRequest.Post(dataCenterUrl + "/rest" + configurationInfoListByFilter, para); 711 data = 712 Json.ToObject<Api_BaseToConfig<Api_Config>>(result); 713 CacheRedis.Cache.Set(RedisKey.ConfigList, data); 714 } 715 if (data.Status) 716 { 717 if (isOutKey && ConfigServer.IsOutside()) 718 { 719 key += "_outside"; 720 } 721 key = key.ToLower(); 722 var firstOrDefault = data.Data.FirstOrDefault(e => e.Identifier.ToLower() == key); 723 if (firstOrDefault != null) 724 { 725 return firstOrDefault.Value; 726 } 727 else 728 { 729 if (key.IndexOf("_outside") > -1) 730 { 731 firstOrDefault = data.Data.FirstOrDefault(e => e.Identifier == key.Substring(0, key.LastIndexOf("_outside"))); 732 if (firstOrDefault != null) 733 return firstOrDefault.Value; 734 } 735 } 736 } 737 return ""; 738 } 739 740 public static string WebPostRequest(string url, string postData) 741 { 742 return CallWebRequest.Post(url, postData); 743 } 744 public static string WebGetRequest(string url) 745 { 746 return CallWebRequest.Get(url); 747 } 748 749 #endregion 750 751 752 #region 參數轉換方法 753 private static string ConvertClassIds(string classIds) 754 { 755 var list = classIds.Split(','); 756 StringBuilder sb = new StringBuilder("{\"class_id_list\": ["); 757 foreach (var s in list) 758 { 759 sb.Append("{\"classId\": \"" + s + "\"},"); 760 } 761 if (list.Any()) 762 sb.Remove(sb.Length - 1, 1); 763 764 sb.Append("]}"); 765 766 return sb.ToString(); 767 } 768 769 private static string ConvertLabIds(string labIds) 770 { 771 var list = labIds.Split(','); 772 StringBuilder sb = new StringBuilder("{\"lab_id_list\": ["); 773 foreach (var s in list) 774 { 775 sb.Append("{\"labId\": \"" + s + "\"},"); 776 } 777 if (list.Any()) 778 sb.Remove(sb.Length - 1, 1); 779 780 sb.Append("]}"); 781 782 return sb.ToString(); 783 } 784 785 private static string ConvertCardNos(string cardNos) 786 { 787 var list = cardNos.Split(','); 788 StringBuilder sb = new StringBuilder("{\"student_cardNos_list\": ["); 789 foreach (var s in list) 790 { 791 sb.Append("{\"stuCardNo\": \"" + s + "\"},"); 792 } 793 if (list.Any()) 794 sb.Remove(sb.Length - 1, 1); 795 796 sb.Append("]}"); 797 798 return sb.ToString(); 799 } 800 #endregion 801 802 803 804 /// <summary> 805 /// 設置公文已讀 806 /// </summary> 807 /// <param name="beginTime"></param> 808 /// <param name="endTime"></param> 809 /// <param name="userId"></param> 810 /// <param name="currentPage"></param> 811 /// <param name="pageSize"></param> 812 /// <returns></returns> 813 public static Api_ToConfig<object> FlowService(string id) 814 { 815 var url = WebConfigManager.GetAppSettings("FlowService"); 816 var data = Json.ToObject<Api_ToConfig<object>>(CallWebRequest.Post(url + "?Copyid=" + id, "")); 817 return data; 818 } 819 820 821 /// <summary> 822 ///獲取OA工做流數據 823 /// </summary> 824 public static string getOAWorkFlowData(string userName, string userId) 825 { 826 var url = GetConfig("platform.application.oa.url") + WebConfigManager.GetAppSettings("OAWorkFlowData"); 827 var data = CallWebRequest.Post(url, "&account=" + userName + "&userId=" + userId); 828 return data; 829 830 } 831 832 public static List<Api_Course> GetDreamClassCourse(string userId) 833 { 834 List<Api_Course> list = new List<Api_Course>(); 835 list = CacheRedis.Cache.Get<List<Api_Course>>(RedisKey.DreamCourse + userId); 836 if (list != null && list.Count > 0) 837 return list; 838 839 var url = GetConfig("platform.system.dreamclass.url", true) + "rest/getTeacherCourseInfo"; 840 var result = Json.ToObject<ApiResult<Api_Course>>(CallWebRequest.Post(url, "&userId=" + userId)); 841 if (result.state) 842 list = result.data; 843 CacheRedis.Cache.Set(RedisKey.DreamCourse + userId, list, 30);//緩存30分鐘失效 844 return list; 845 } 846 847 /// <summary> 848 /// 用戶信息 849 /// </summary> 850 /// <param name="userId"></param> 851 /// <returns></returns> 852 public static Api_User GetUserInfoByUserName(string userName) 853 { 854 var model = new Api_User(); 855 var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/getUserInfoByUserName"; 856 var result = Json.ToObject<ApiBase<Api_User>>(CallWebRequest.Post(url, "&userName=" + userName)); 857 if (result.status == true && result.data != null) 858 model = result.data; 859 return model; 860 } 861 862 public static Api_User GetUserInfoByUserId(string userId) 863 { 864 var model = new Api_User(); 865 var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/getUserInfoByUserId"; 866 var result = Json.ToObject<ApiBase<Api_User>>(CallWebRequest.Get(url + "?userId=" + userId)); 867 if (result.status == true && result.data != null) 868 model = result.data; 869 return model; 870 } 871 872 public static Api_User GetUserByUserId(string userId) 873 { 874 var model = new Api_User(); 875 var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/getUserByUserId"; 876 var result = Json.ToObject<ApiBase<Api_User>>(CallWebRequest.Get(url + "?userId=" + userId)); 877 if (result.status == true && result.data != null) 878 model = result.data; 879 return model; 880 } 881 882 883 public static ApiBase<string> UserExist(string userName) 884 { 885 ApiBase<string> result = new ApiBase<string>(); 886 var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/checkUserExists"; 887 result = Json.ToObject<ApiBase<string>>(CallWebRequest.Post(url, "&userName=" + userName)); 888 return result; 889 890 } 891 public static ApiBase<string> CheckUserPwd(string userName, string pwd) 892 { 893 ApiBase<string> result = new ApiBase<string>(); 894 var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/checkUserPsw"; 895 result = Json.ToObject<ApiBase<string>>(CallWebRequest.Post(url, "&userName=" + userName + "&psw=" + pwd)); 896 return result; 897 898 } 899 public static ApiBase<Api_AnswerQuestion> GetAnswerQuestion(string userName) 900 { 901 ApiBase<Api_AnswerQuestion> result = new ApiBase<Api_AnswerQuestion>(); 902 var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/safety/getSafetyByUserName"; 903 result = Json.ToObject<ApiBase<Api_AnswerQuestion>>(CallWebRequest.Post(url, "&userName=" + userName)); 904 return result; 905 } 906 907 public static ApiBase<string> ResetUserPassword(string userName, string newPassWord) 908 { 909 ApiBase<string> result = new ApiBase<string>(); 910 var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/resetUserPasswordByUserName"; 911 result = Json.ToObject<ApiBase<string>>(CallWebRequest.Post(url, "&userName=" + userName + "&newPassWord=" + newPassWord)); 912 return result; 913 } 914 public static ApiBase<string> ChangeUserSafeAnswer(string userId, string answer1, string answer2, string answer3, string safeId) 915 { 916 ApiBase<string> result = new ApiBase<string>(); 917 var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/safety/batchUpdageSafety"; 918 result = Json.ToObject<ApiBase<string>>(CallWebRequest.Post(url, "&data=[{editor:\"" + userId + "\",safetyAnswerOne:\"" + answer1 + "\",safetyAnswerTwo:\"" + answer2 + "\",safetyAnswerThree:\"" + answer3 + "\",safetyId:" + safeId + "}]")); 919 return result; 920 } 921 922 public static ApiBase<string> UpdateUserPhoto(string userId, string userPhoto) 923 { 924 ApiBase<string> result = new ApiBase<string>(); 925 var url = WebConfigManager.GetAppSettings("DataCenterUrl") + "/rest/user/updataUserInfo"; 926 result = Json.ToObject<ApiBase<string>>(CallWebRequest.Post(url, "&data=[{userId:\"" + userId + "\",userPhoto:\"" + userPhoto + "\"}]")); 927 return result; 928 } 929 930 public static Api_DreamClassUserInfo GetDreamClassUser(string userId) 931 { 932 var model = new Api_DreamClassUserInfo(); 933 //model = CacheRedis.Cache.Get<Api_DreamClassUserInfo>(RedisKey.DreamCourseUser + userId); 934 var url = GetConfig("platform.system.dreamclass.url", true) + "rest/getUserInfo"; 935 var result = Json.ToObject<ApiBase<Api_DreamClassUserInfo>>(CallWebRequest.Post(url, "&userId=" + userId)); 936 if (result.state == true && result.data != null) 937 { 938 model = result.data; 939 //CacheRedis.Cache.Set(RedisKey.DreamCourseUser+userId,model); 940 } 941 942 return model; 943 } 944 945 public static List<Api_BitCourse> GetBitCourseList(string userName) 946 { 947 List<Api_BitCourse> list = new List<Api_BitCourse>(); 948 list = CacheRedis.Cache.Get<List<Api_BitCourse>>(RedisKey.BitCourse + userName); 949 if (list != null && list.Count > 0) 950 return list; 951 try 952 { 953 var url = GetConfig("platform.system.szhjxpt.url", true) + "/Services/DtpServiceWJL.asmx/GetMyCourseByLoginName"; 954 var result = Json.ToObject<ApiConfig<Api_BitCourse>>(CallWebRequest.Post(url, "&loginName=" + userName)); 955 956 if (result.success) 957 list = result.datas; 958 CacheRedis.Cache.Set(RedisKey.BitCourse + userName, list, 30);//緩存30分鐘失效 959 } 960 catch (Exception exception) 961 { 962 list = new List<Api_BitCourse>(); 963 Log.Error(exception.Message); 964 } 965 966 return list; 967 } 968 }
一個簡單的例子
1 string __url = "http://localhost:4090/API/Referal/Visit"; 2 string param = "{ \"Year\": 2019,\"Month\": 4,\"Operator\":\"sys_overseas\"}"; 3 WebRequestHelper.OnPOST<JsonData<RRData>>(__url, param);
1 class WebRequestHelper 2 { 3 /// <summary> 4 /// 5 /// </summary> 6 /// <param name="url"></param> 7 /// <param name="param"></param> 8 /// <returns></returns> 9 public static string OnPOST(string url, string param = null) 10 { 11 var req = WebRequest.Create(url) as HttpWebRequest; 12 req.Method = "POST"; 13 req.ContentType = "application/json"; 14 15 using (StreamWriter reWriter = new StreamWriter(req.GetRequestStream())) 16 { 17 reWriter.Write(param); 18 reWriter.Close(); 19 } 20 var res = req.GetResponse(); 21 22 using (var reader = new StreamReader(res.GetResponseStream())) 23 { 24 string _json = reader.ReadToEnd(); 25 26 return _json; 27 } 28 29 } 30 31 public static T OnPOST<T>(string url, string param = null) where T : new() 32 { 33 //var req = WebRequest.Create(url) as HttpWebRequest; 34 //using (var reqWrite=new StreamWriter(req.GetRequestStream())) 35 //{ 36 // reqWrite.Write(param); 37 // reqWrite.Close(); 38 //} 39 40 //var res = req.GetResponse(); 41 //using (var reader=new StreamReader(res.GetResponseStream())) 42 //{ 43 // string _json= reader.ReadToEnd(); 44 string _json = OnPOST(url, param); 45 return JsonConvert.DeserializeObject<T>(_json); 46 //} 47 } 48 49 50 }