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请求程序模拟有所帮助。