C#中编程调用WebAPI,其中用到HttpWebRequest类和HttpWebResponse类。
一、命名空间
HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数据的最好选择。
这两个类位 于System.Net命名空间。用来使用户通过HTTP协议和服务器交互。
二、HttpWebRequest的作用
HttpWebRequest对HTTP协议进行了完整的封装,对HTTP协议中的 Header, Content, Cookie 都做了属性和方法的支持,很容易就能编写出一个模拟浏览器自动登录的程序。
三、属性
HttpWebRequest的属性对于轻量级的自动化测试程序是超级重大的。
对请求重定向(request redirections)的次数进行了限制, 设置了超时限制。
- AllowAutoRedirect:获取或设置一个值,该值指示请求是否应跟随重定向响应。
- CookieContainer:获取或设置与此请求关联的cookie。
- Credentials:获取或设置请求的身份验证信息。
- KeepAlive:获取或设置一个值,该值指示是否与 Internet 资源建立持久性连接。
- MaximumAutomaticRedirections:获取或设置请求将跟随的重定向的最大数目。
- Proxy:获取或设置请求的代理信息。
- SendChunked:获取或设置一个值,该值指示是否将数据分段发送到 Internet 资源。
- Timeout:获取或设置请求的超时值。
- UserAgent:获取或设置 User-agent HTTP 标头的值
四、使用方法
- 请注意,HttpWebRequest对象不是利用new关键字通过构 造函数来创建的,而是利用工厂机制(factory mechanism)通过Create()方法来创建的。(创建即发送)
- 接下来调用 HttpWebRequest.GetResponse()方法返回的是一个HttpWebResponse对象。(接收过程)
- 你可以把HTTP响应的数据流 (stream)绑定到一个StreamReader对象,然后就可以通过ReadToEnd()方法把整个HTTP响应作为一个字符串取回。(取回返回值)
- 也可以通过 StreamReader.ReadLine()方法逐行取回HTTP响应的内容。
五、HttpWebRequest提交数据的方式
HttpWebRequest提交数据方式实则就只有两种:
- GET 方式
- POST 方式
方式1. GET 方式
GET 方式通过在网络地址附加参数来完成数据的提交,
列如在地址 http://www.google.com/webhp?hl=zh-CN 中,
前面部分 http://www.google.com/webhp 表明数据提交的网址,
后面部分 hl=zh-CN 表明附加的参数,
其中 hl 表明一个键(key),
zh-CN 表明这个键对应的值(value)。
程序代码如下:
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create("http://www.google.com/webhp?hl=zh-CN" );
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{
//在这里对接收到的页面内容进行处理
}
方式2. POST 方式
POST 方式通过在页面内容中填写参数的方法来完成数据的提交,参数的格式和 GET 方式一样,是类似于 hl=zh-CN&newwindow=1 这样的结构。程序代码如下:
string param = "hl=zh-CN&newwindow=1"; //参数
byte[] bs = Encoding.ASCII.GetBytes(param); //参数转化为ascii码
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.google.com/intl/zh-CN/" ); //创建request
req.Method = "POST"; //确定传值的方式,此处为post方式传值
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = bs.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse wr = req.GetResponse())
{ //在这里对接收到的页面内容进行处理
}
在上面的代码中,我们访问了google 的网址,分别以 GET 和 POST 方式提交了数据,并接收了返回的页面内容。不过,如果提交的参数中含有中文,那么这样的处理是不够的,需要对其进行编码,让对方网站能够识别。
方式3. 使用 GET 方式提交中文数据
GET 方式通过在网络地址中附加参数来完成数据提交,对于中文的编码,常用的有 gb2312 和 utf8 两种,用 gb2312 方式编码访问的程序代码如下:
Encoding myEncoding = Encoding.GetEncoding("gb2312"); //确定用哪种中文编码方式
string address = "http://www.baidu.com/s?" + HttpUtility.UrlEncode("参数一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding); //拼接数据提交的网址和经过中文编码后的中文参数
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address); //创建request
req.Method = "GET"; //确定传值方式,此处为get方式
using (WebResponse wr = req.GetResponse())
{ //在这里对接收到的页面内容进行处理
}
在上面的程序代码中,
我们以 GET 方式访问了网址 http://www.baidu.com/s ,
传递了参数“参数一=值一”,
由于无法告知对方提交数据的编码类型,
所以编码方式要以对方的网站为标准。
常见的网站中, www.baidu.com (百度)的编码方式是 gb2312,
www.google.com (谷歌)的编码方式是 utf8。
方式4. 使用 POST 方式提交中文数据
POST 方式通过在页面内容中填写参数的方法来完成数据的提交,由于提交的参数中可以说明使用的编码方式,所以理论上能获得更大的兼容性。用 gb2312 方式编码访问的程序代码如下:
Encoding myEncoding = Encoding.GetEncoding("gb2312"); //确定中文编码方式。此处用gb2312
string param = HttpUtility.UrlEncode("参数一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding) + "&" + HttpUtility.UrlEncode("参数二", myEncoding) + "=" + HttpUtility.UrlEncode("值二", myEncoding);
byte[] postBytes = Encoding.ASCII.GetBytes(param); //将参数转化为assic码
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.baidu.com/s" );
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded;charset=gb2312";
req.ContentLength = postBytes.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse wr = req.GetResponse())
{
//在这里对接收到的页面内容进行处理
}
从上面的代码可以看出, POST 中文数据的时候,先使用 UrlEncode 方法将中文字符转换为编码后的 ASCII 码,然后提交到服务器,提交的时候可以说明编码的方式,用来使对方服务器能够正确的解析。
六、公共方法
#region 公共方法
/// <summary>
/// Get数据接口
/// </summary>
/// <param name="getUrl">接口地址</param>
/// <returns></returns>
private static string GetWebRequest(string getUrl)
{
string responseContent = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(getUrl);
request.ContentType = "application/json";
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//在这里对接收到的页面内容进行处理
using (Stream resStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(resStream, Encoding.UTF8))
{
responseContent = reader.ReadToEnd().ToString();
}
}
return responseContent;
}
/// <summary>
/// Post数据接口
/// </summary>
/// <param name="postUrl">接口地址</param>
/// <param name="paramData">提交json数据</param>
/// <param name="dataEncode">编码方式(Encoding.UTF8)</param>
/// <returns></returns>
private static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
{
string responseContent = string.Empty;
try
{
byte[] byteArray = dataEncode.GetBytes(paramData); //转化
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded";
webReq.ContentLength = byteArray.Length;
using (Stream reqStream = webReq.GetRequestStream())
{
reqStream.Write(byteArray, 0, byteArray.Length);//写入参数
//reqStream.Close();
}
using (HttpWebResponse response = (HttpWebResponse)webReq.GetResponse())
{
//在这里对接收到的页面内容进行处理
using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default))
{
responseContent = sr.ReadToEnd().ToString();
}
}
}
catch (Exception ex)
{
return ex.Message;
}
return responseContent;
}
#endregion
//post支持cookie
七、参考资料
1、心所欲的博客(https://www.cnblogs.com/zoujinhua/p/11313396.html)






![[C++探索之旅] 第一部分第十一课:小练习,猜单词 - 鹿快](https://img.lukuai.com/blogimg/20251015/da217e2245754101b3d2ef80869e9de2.jpg)










暂无评论内容