工作中的項目要用到別家的網絡短信平台,工作中遇到中文編碼的問題,特總結以備忘。
GET方法:
public string DoWebRequest(string url) { HttpWebResponse webResponse = null; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.Method = "POST"; string responseStr = null; webRequest.Timeout = 50000; webRequest.ContentType = "text/html; charset=gb2312"; try { //嘗試獲得要請求的URL的返回消息 webResponse = (HttpWebResponse)webRequest.GetResponse(); } catch (WebException e) { //發生網絡錯誤時,獲取錯誤響應信息 responseStr = "發生網絡錯誤!請稍后再試"; } catch (Exception e) { //發生異常時把錯誤信息當作錯誤信息返回 responseStr = "發生錯誤:" + e.Message; } finally { if (webResponse != null) { //獲得網絡響應流 using (StreamReader responseReader = new StreamReader(webResponse.GetResponseStream(), Encoding.GetEncoding("GB2312"))) { responseStr = responseReader.ReadToEnd();//獲得返回流中的內容 } webResponse.Close();//關閉web響應流 } } return responseStr; }
注意:url中的中文,要先用HttpUtility.UrlEncode("內容",編碼) 用服務器接收的編碼,編碼一下。
POST方法:
private string DoWebRequestByPost(string url, string param) { HttpWebResponse webResponse = null; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); //使用post方式提交 webRequest.Method = "POST"; string responseStr = null; webRequest.Timeout = 50000; //要post的字節數組 byte[] postBytes = encoding.GetBytes(param); webRequest.ContentType = "application/x-www-form-urlencoded;"; webRequest.ContentLength = postBytes.Length; using (Stream reqStream = webRequest.GetRequestStream()) { reqStream.Write(postBytes, 0, postBytes.Length); } try { //嘗試獲得要請求的URL的返回消息 webResponse = (HttpWebResponse)webRequest.GetResponse(); } catch (Exception) { //出錯后直接拋出 throw; } finally { if (webResponse != null) { //獲得網絡響應流 using (StreamReader responseReader = new StreamReader(webResponse.GetResponseStream(), encoding)) { responseStr = responseReader.ReadToEnd();//獲得返回流中的內容 } webResponse.Close();//關閉web響應流 } } return responseStr; }
encoding為服務器接收的編碼,例如:Encoding.GetEncoding("GBK")等
param post請求的參數 param1=123¶m2=中國¶m3=abc 這樣的格式,中文部分不用使用編碼,方法內轉成byte[]時 會進行編碼。