http請求和資料丟失問題
阿新 • • 發佈:2019-01-08
呼叫方式如:SentHttpRequest("param=1¶m2=2");
注:引數值可用 Uri.EscapeDataString或Uri.EscapeUriString對引數轉譯防止特殊符號丟失資料情況。
public string SentHttpRequest(string param)
{//請求url
string url = "http://baidu.com/a.html";
//定義request並設定request的路徑
WebRequest request = WebRequest.Create(url);
//定義請求的方式
request.Method = "POST";
//初始化request引數
string postData = param; //"action=send&broadcast=Y&uri=112332&username=f8df247d0b2b4277b122f68c94c2caab";
//設定引數的編碼格式,解決中文亂碼
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
//設定request的MIME型別及內容長度
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
//開啟request字元流
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//定義response為前面的request響應
WebResponse response = request.GetResponse();
//獲取相應的狀態程式碼
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
//定義response字元流
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();//讀取所有
Console.WriteLine(responseFromServer);
//關閉資源
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}