C# HTTP Request請求程序模擬是如何實現的呢?我們在實現發送請求的操作是會用到哪些方法呢?那麼下面我們來看看具體的實現方法,使用下面的代碼片段時,記得 在程序的引用上右鍵,然後添加引用,添加 System.Web. 就可以使用下面的代碼了.
C# HTTP Request請求程序模擬實例
using System.Net;
using System.IO;
using System.Web;
/********************
*C# HTTP Request請求程序模擬***
* 向服務器送出請求
* */
public string SendRequest(string param)
{
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(param);
HttpWebRequest request =
(HttpWebRequest)HttpWebRequest.Create(this.url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream sm = request.GetRequestStream();
sm.Write(data, 0, data.Length);
sm.Close();
HttpWebResponse response =
(HttpWebResponse)request.GetResponse();
if (response.StatusCode.ToString() != "OK")
{
MessageBox.Show(response.StatusDescription.ToString());
return "";
}
StreamReader myreader = new StreamReader(
response.GetResponseStream(), Encoding.UTF8);
string responseText = myreader.ReadToEnd();
return responseText;
}
/**C# HTTP Request請求程序模擬
* 進行UTF-8的URL編碼轉換(針對漢字參數)
* */
public string EncodeConver(string instring)
{
return HttpUtility.UrlEncode(instring, Encoding.UTF8);
}
/**C# HTTP Request請求程序模擬
* 進行登錄操作並返回相應結果
* */
public bool DoLogin(string username,
string password)
{
password = System.Web.Security.FormsAuthentication.
HashPasswordForStoringInConfigFile(password, "MD5");
string param = string.Format("do=login&u={0}&p={1}",
this.EncodeConver(username), this.EncodeConver(password));
string result = this.SendRequest(param);
// MessageBox.Show(result); 解析 Result ,我這裏是作爲一個XML Document來解析的
return true;
}
C# HTTP Request請求程序模擬的基本內容就向你介紹到這裏,希望對你瞭解和學習C# HTTP Request請求程序模擬有所幫助。