轉載:https://blog.csdn.net/zhruifei/article/details/78356347
一、HttpWebRequest與HttpWebResponce的概念:
用途范圍:HttpWebRequest和HttpWebResponse可以發送和接受任何類型數據
1、HttpWebRequest和HttpWebResponse類是用於發送和接收HTTP數據的最好選擇。
2、命名空間:System.Net
3、HttpWebRequest對象不是利用new關鍵字創建的(通過構造函數)。 而是利用Create()方法創建的。
4、你可能預計需要顯示地調用一個“Send”方法,實際上不需要。
5、調用 HttpWebRequest.GetResponse()方法返回的是一個HttpWebResponse對象
6、你可以把HTTP響應的數據流 (stream)綁定到一個StreamReader對象,然后就可以通過ReadToEnd()方法把整個HTTP響應作為一個字符串取回。也可以通過 StreamReader.ReadLine()方法逐行取回HTTP響應的內容。
下面是HttpWebRequest的一些屬性,這些屬性對於輕量級的自動化測試程序是非常重要的。
a) AllowAutoRedirect:獲取或設置一個值,該值指示請求是否應跟隨重定向響應。
b)CookieContainer:獲取或設置與此請求關聯的cookie。
c)Credentials:獲取或設置請求的身份驗證信息。
d)KeepAlive:獲取或設置一個值,該值指示是否與 Internet 資源建立持久性連接。
e)MaximumAutomaticRedirections:獲取或設置請求將跟隨的重定向的最大數目。
f) Proxy:獲取或設置請求的代理信息。
g)SendChunked:獲取或設置一個值,該值指示是否將數據分段發送到 Internet 資源。
h)Timeout:獲取或設置請求的超時值。
i) UserAgent:獲取或設置 User-agent HTTP 標頭的值
C# HttpWebRequest提交數據方式其實就是GET和POST兩種
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)。程序代碼如下:
1 HttpWebRequest req = 2 (HttpWebRequest)HttpWebRequest.Create("http://www.google.com/webhp?hl=zh-CN" ); 3 req.Method = "GET"; 4 using (WebResponse wr = req.GetResponse()) 5 { 6 //在這里對接收到的頁面內容進行處理 7 }
2. POST 方式。
POST 方式通過在頁面內容中填寫參數的方法來完成數據的提交,參數的格式和 GET 方式一樣,是類似於 hl=zh-CN&newwindow=1 這樣的結構。程序代碼如下:
1 string param = "hl=zh-CN&newwindow=1"; //參數 2 byte[] bs = Encoding.ASCII.GetBytes(param); //參數轉化為ascii碼 3 HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create("http://www.google.com/intl/zh-CN/" ); //創建request 4 req.Method = "POST"; //確定傳值的方式,此處為post方式傳值 5 req.ContentType = "application/x-www-form-urlencoded"; 6 req.ContentLength = bs.Length; 7 using (Stream reqStream = req.GetRequestStream()) 8 { 9 reqStream.Write(bs, 0, bs.Length); 10 } 11 using (WebResponse wr = req.GetResponse()) 12 { 13 //在這里對接收到的頁面內容進行處理 14 }
3. 使用 GET 方式提交中文數據。
GET 方式通過在網絡地址中附加參數來完成數據提交,對於中文的編碼,常用的有 gb2312 和 utf8 兩種,用 gb2312 方式編碼訪問的程序代碼如下:
1 Encoding myEncoding = Encoding.GetEncoding("gb2312"); //確定用哪種中文編碼方式 2 string address = "http://www.baidu.com/s?"+ HttpUtility.UrlEncode("參數一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding); //拼接數據提交的網址和經過中文編碼后的中文參數 3 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address); //創建request 4 req.Method = "GET"; //確定傳值方式,此處為get方式 5 using (WebResponse wr = req.GetResponse()) 6 { 7 //在這里對接收到的頁面內容進行處理 8 }
在上面的程序代碼中,我們以 GET 方式訪問了網址 http://www.baidu.com/s ,傳遞了參數“參數一=值一”,由於無法告知對方提交數據的編碼類型,所以編碼方式要以對方的網站為標准。常見的網站中, www.baidu.com (百度)的編碼方式是 gb2312, www.google.com (谷歌)的編碼方式是 utf8。
4. 使用 POST 方式提交中文數據。
POST 方式通過在頁面內容中填寫參數的方法來完成數據的提交,由於提交的參數中可以說明使用的編碼方式,所以理論上能獲得更大的兼容性。用 gb2312 方式編碼訪問的程序代碼如下:
1 Encoding myEncoding = Encoding.GetEncoding("gb2312"); //確定中文編碼方式。此處用gb2312 2 string param = HttpUtility.UrlEncode("參數一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding) + "&" + HttpUtility.UrlEncode("參數二", myEncoding) + "=" + HttpUtility.UrlEncode("值二", myEncoding); 3 byte[] postBytes = Encoding.ASCII.GetBytes(param); //將參數轉化為assic碼 4 HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.baidu.com/s" ); 5 req.Method = "POST"; 6 req.ContentType = "application/x-www-form-urlencoded;charset=gb2312"; 7 req.ContentLength = postBytes.Length; 8 using (Stream reqStream = req.GetRequestStream()) 9 { 10 reqStream.Write(bs, 0, bs.Length); 11 } 12 using (WebResponse wr = req.GetResponse()) 13 { 14 //在這里對接收到的頁面內容進行處理 15 }
從上面的代碼可以看出, POST 中文數據的時候,先使用 UrlEncode 方法將中文字符轉換為編碼后的 ASCII 碼,然后提交到服務器,提交的時候可以說明編碼的方式,用來使對方服務器能夠正確的解析。
以上列出了客戶端程序使用HTTP協議與服務器交互的情況,常用的是 GET 和 POST 方式。
現在流行的 WebService 也是通過 HTTP 協議來交互的,使用的是 POST 方法。與以上稍有所不同的是, WebService 提交的數據內容和接收到的數據內容都是使用了 XML 方式編碼。所以, HttpWebRequest 也可以使用在調用 WebService 的情況下。
C# HttpWebRequest提交數據方式的基本內容就向你介紹到這里,希望對你了解和學習C# HttpWebRequest提交數據方式有所幫助。

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
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";
C#通過WebClient/HttpWebRequest實現http的post/get方法
1.POST方法(httpWebRequest)

1 //body是要傳遞的參數,格式"roleId=1&uid=2" 2 //post的cotentType填寫:"application/x-www-form-urlencoded" 3 //soap填寫:"text/xml; charset=utf-8" 4 public static string PostHttp(string url, string body, string contentType) 5 { 6 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); 7 8 httpWebRequest.ContentType = contentType; 9 httpWebRequest.Method = "POST"; 10 httpWebRequest.Timeout = 20000; 11 12 byte[] btBodys = Encoding.UTF8.GetBytes(body); 13 httpWebRequest.ContentLength = btBodys.Length; 14 httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length); 15 16 HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); 17 StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()); 18 string responseContent = streamReader.ReadToEnd(); 19 20 httpWebResponse.Close(); 21 streamReader.Close(); 22 httpWebRequest.Abort(); 23 httpWebResponse.Close(); 24 25 return responseContent; 26 }
2.POST方法(WebClient)
/// <summary> /// 通過WebClient類Post數據到遠程地址,需要Basic認證; /// 調用端自己處理異常 /// </summary> /// <param name="uri"></param> /// <param name="paramStr">name=張三&age=20</param> /// <param name="encoding">請先確認目標網頁的編碼方式</param> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> public static string Request_WebClient(string uri, string paramStr, Encoding encoding, string username, string password) { if (encoding == null) encoding = Encoding.UTF8; string result = string.Empty; WebClient wc = new WebClient(); // 采取POST方式必須加的Header wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); byte[] postData = encoding.GetBytes(paramStr); if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) { wc.Credentials = GetCredentialCache(uri, username, password); wc.Headers.Add("Authorization", GetAuthorization(username, password)); } byte[] responseData = wc.UploadData(uri, "POST", postData); // 得到返回字符流 return encoding.GetString(responseData);// 解碼 }
3.Get方法(httpWebRequest)

1 public static string GetHttp(string url, HttpContext httpContext) 2 { 3 string queryString = "?"; 4 5 foreach (string key in httpContext.Request.QueryString.AllKeys) 6 { 7 queryString += key + "=" + httpContext.Request.QueryString[key] + "&"; 8 } 9 10 queryString = queryString.Substring(0, queryString.Length - 1); 11 12 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + queryString); 13 14 httpWebRequest.ContentType = "application/json"; 15 httpWebRequest.Method = "GET"; 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 29 return responseContent; 30 }
4.basic驗證的WebRequest/WebResponse

1 /// <summary> 2 /// 通過 WebRequest/WebResponse 類訪問遠程地址並返回結果,需要Basic認證; 3 /// 調用端自己處理異常 4 /// </summary> 5 /// <param name="uri"></param> 6 /// <param name="timeout">訪問超時時間,單位毫秒;如果不設置超時時間,傳入0</param> 7 /// <param name="encoding">如果不知道具體的編碼,傳入null</param> 8 /// <param name="username"></param> 9 /// <param name="password"></param> 10 /// <returns></returns> 11 public static string Request_WebRequest(string uri, int timeout, Encoding encoding, string username, string password) 12 { 13 string result = string.Empty; 14 15 WebRequest request = WebRequest.Create(new Uri(uri)); 16 17 if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) 18 { 19 request.Credentials = GetCredentialCache(uri, username, password); 20 request.Headers.Add("Authorization", GetAuthorization(username, password)); 21 } 22 23 if (timeout > 0) 24 request.Timeout = timeout; 25 26 WebResponse response = request.GetResponse(); 27 Stream stream = response.GetResponseStream(); 28 StreamReader sr = encoding == null ? new StreamReader(stream) : new StreamReader(stream, encoding); 29 30 result = sr.ReadToEnd(); 31 32 sr.Close(); 33 stream.Close(); 34 35 return result; 36 } 37 38 #region # 生成 Http Basic 訪問憑證 # 39 40 private static CredentialCache GetCredentialCache(string uri, string username, string password) 41 { 42 string authorization = string.Format("{0}:{1}", username, password); 43 44 CredentialCache credCache = new CredentialCache(); 45 credCache.Add(new Uri(uri), "Basic", new NetworkCredential(username, password)); 46 47 return credCache; 48 } 49 50 private static string GetAuthorization(string username, string password) 51 { 52 string authorization = string.Format("{0}:{1}", username, password); 53 54 return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization)); 55 } 56 57 #endregion