浅析 C# WinForm程序模拟HTTP Request请求

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-8URL编码转换(针对汉字参数)  

 * */ 

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

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值