C#中HttpWebRequest的用法详解(转载)
1、HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数据的最好选择。
2、命名空间:System.Net
3、HttpWebRequest对象不是利用new关键字创建的(通过构造函数)。 而是利用Create()方法创建的。
4、你可能预计需要显示地调用一个“Send”方法,实际上不需要。
5、调用 HttpWebRequest.GetResponse()方法返回的是一个HttpWebResponse对象
6、你可以把HTTP响应的数据流 (stream)绑定到一个StreamReader对象,然后就可以通过ReadToEnd()方法把整个HTTP响应作为一个字符串取回。也可以通过 StreamReader.ReadLine()方法逐行取回HTTP响应的内容。
下面是HttpWebRequest的一些属性,这些属性对于轻量级的自动化测试程序是非常重要的。
a) AllowAutoRedirect:获取或设置一个值,该值指示请求是否应跟随重定向响应。
b)CookieContainer:获取或设置与此请求关联的cookie。
c)Credentials:获取或设置请求的身份验证信息。
d)KeepAlive:获取或设置一个值,该值指示是否与 Internet 资源建立持久性连接。
e)MaximumAutomaticRedirections:获取或设置请求将跟随的重定向的最大数目。
f) Proxy:获取或设置请求的代理信息。
g)SendChunked:获取或设置一个值,该值指示是否将数据分段发送到 Internet 资源。
h)Timeout:获取或设置请求的超时值。
i) UserAgent:获取或设置 User-agent HTTP 标头的值
C# HttpWebRequest提交数据方式其实就是GET和POST两种
C# HttpWebRequest的作用:
HttpWebRequest对HTTP协议进行了完整的封装,对HTTP协议中的 Header, Content, Cookie 都做了属性和方法的支持,很容易就能编写出一个模拟浏览器自动登录的程序。
C# HttpWebRequest提交数据方式:
程序使用HTTP协议和服务器交互主要是进行数据的提交,通常数据的提交是通过 GET 和 POST 两种方式来完成,
C# HttpWebRequest提交数据方式:
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, , bs.Length);
}
using (WebResponse wr = req.GetResponse())
{
//在这里对接收到的页面内容进行处理
}
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, , bs.Length);
}
using (WebResponse wr = req.GetResponse())
{
//在这里对接收到的页面内容进行处理
}
从上面的代码可以看出, POST 中文数据的时候,先使用 UrlEncode 方法将中文字符转换为编码后的 ASCII 码,然后提交到服务器,提交的时候可以说明编码的方式,用来使对方服务器能够正确的解析。
以上列出了客户端程序使用HTTP协议与服务器交互的情况,常用的是 GET 和 POST 方式。
现在流行的 WebService 也是通过 HTTP 协议来交互的,使用的是 POST 方法。与以上稍有所不同的是, WebService 提交的数据内容和接收到的数据内容都是使用了 XML 方式编码。所以, HttpWebRequest 也可以使用在调用 WebService 的情况下。
C# HttpWebRequest提交数据方式的基本内容就向你介绍到这里,希望对你了解和学习C# HttpWebRequest提交数据方式有所帮助。
#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, , 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
OAuth头部
//构造OAuth头部
StringBuilder oauthHeader = new StringBuilder();
oauthHeader.AppendFormat("OAuth realm=\"\", oauth_consumer_key={0}, ", apiKey);
oauthHeader.AppendFormat("oauth_nonce={0}, ", nonce);
oauthHeader.AppendFormat("oauth_timestamp={0}, ", timeStamp);
oauthHeader.AppendFormat("oauth_signature_method={0}, ", "HMAC-SHA1");
oauthHeader.AppendFormat("oauth_version={0}, ", "1.0");
oauthHeader.AppendFormat("oauth_signature={0}, ", sig);
oauthHeader.AppendFormat("oauth_token={0}", accessToken); //构造请求
StringBuilder requestBody = new StringBuilder("");
Encoding encoding = Encoding.GetEncoding("utf-8");
byte[] data = encoding.GetBytes(requestBody.ToString()); // Http Request的设置
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Headers.Set("Authorization", oauthHeader.ToString());
//request.Headers.Add("Authorization", authorization);
request.ContentType = "application/atom+xml";
request.Method = "GET";
C#通过WebClient/HttpWebRequest实现http的post/get方法
1.POST方法(httpWebRequest)
//body是要传递的参数,格式"roleId=1&uid=2"
//post的cotentType填写:"application/x-www-form-urlencoded"
//soap填写:"text/xml; charset=utf-8"
public static string PostHttp(string url, string body, string contentType)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.ContentType = contentType;
httpWebRequest.Method = "POST";
httpWebRequest.Timeout = ; byte[] btBodys = Encoding.UTF8.GetBytes(body);
httpWebRequest.ContentLength = btBodys.Length;
httpWebRequest.GetRequestStream().Write(btBodys, , btBodys.Length); HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
string responseContent = streamReader.ReadToEnd(); httpWebResponse.Close();
streamReader.Close();
httpWebRequest.Abort();
httpWebResponse.Close(); return responseContent;
}
2.POST方法(WebClient)
/// <summary>
/// 通过WebClient类Post数据到远程地址,需要Basic认证;
/// 调用端自己处理异常
/// </summary>
/// <param name="uri"></param>
/// <param name="paramStr">name=张三&age=20</param>
/// <param name="encoding">请先确认目标网页的编码方式</param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
public static string Request_WebClient(string uri, string paramStr, Encoding encoding, string username, string password)
{
if (encoding == null)
encoding = Encoding.UTF8; string result = string.Empty; WebClient wc = new WebClient(); // 采取POST方式必须加的Header
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); byte[] postData = encoding.GetBytes(paramStr); if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
wc.Credentials = GetCredentialCache(uri, username, password);
wc.Headers.Add("Authorization", GetAuthorization(username, password));
} byte[] responseData = wc.UploadData(uri, "POST", postData); // 得到返回字符流
return encoding.GetString(responseData);// 解码
}
3.Get方法(httpWebRequest)
public static string GetHttp(string url, HttpContext httpContext)
{
string queryString = "?"; foreach (string key in httpContext.Request.QueryString.AllKeys)
{
queryString += key + "=" + httpContext.Request.QueryString[key] + "&";
} queryString = queryString.Substring(, queryString.Length - ); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + queryString); httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
httpWebRequest.Timeout = ; //byte[] btBodys = Encoding.UTF8.GetBytes(body);
//httpWebRequest.ContentLength = btBodys.Length;
//httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length); HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
string responseContent = streamReader.ReadToEnd(); httpWebResponse.Close();
streamReader.Close(); return responseContent;
}
4.basic验证的WebRequest/WebResponse
/// <summary>
/// 通过 WebRequest/WebResponse 类访问远程地址并返回结果,需要Basic认证;
/// 调用端自己处理异常
/// </summary>
/// <param name="uri"></param>
/// <param name="timeout">访问超时时间,单位毫秒;如果不设置超时时间,传入0</param>
/// <param name="encoding">如果不知道具体的编码,传入null</param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
public static string Request_WebRequest(string uri, int timeout, Encoding encoding, string username, string password)
{
string result = string.Empty; WebRequest request = WebRequest.Create(new Uri(uri)); if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
request.Credentials = GetCredentialCache(uri, username, password);
request.Headers.Add("Authorization", GetAuthorization(username, password));
} if (timeout > )
request.Timeout = timeout; WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader sr = encoding == null ? new StreamReader(stream) : new StreamReader(stream, encoding); result = sr.ReadToEnd(); sr.Close();
stream.Close(); return result;
} #region # 生成 Http Basic 访问凭证 # private static CredentialCache GetCredentialCache(string uri, string username, string password)
{
string authorization = string.Format("{0}:{1}", username, password); CredentialCache credCache = new CredentialCache();
credCache.Add(new Uri(uri), "Basic", new NetworkCredential(username, password)); return credCache;
} private static string GetAuthorization(string username, string password)
{
string authorization = string.Format("{0}:{1}", username, password); return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization));
} #endregion
C#中HttpWebRequest的用法详解(转载)的更多相关文章
- 【转】C#中HttpWebRequest的用法详解
本文实例讲述了C#中HttpWebRequest的用法.分享给大家供大家参考.具体如下: HttpWebRequest类主要利用HTTP 协议和服务器交互,通常是通过 GET 和 POST 两种方式来 ...
- C#中HttpWebRequest的用法详解
原文链接:http://www.cnblogs.com/love201314/p/5029312.html 1.HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数 ...
- python中yield的用法详解-转载
原文链接:https://blog.csdn.net/mieleizhi0522/article/details/82142856 ,今天在写python爬虫的时候,循环的时候用到了yield,于是搜 ...
- css3中user-select的用法详解
css3中user-select的用法详解 user-select属性是css3新增的属性,用于设置用户是否能够选中文本.可用于除替换元素外的所有元素,以下是user-select的主要用法和注意事项 ...
- C#中string.format用法详解
C#中string.format用法详解 本文实例总结了C#中string.format用法.分享给大家供大家参考.具体分析如下: String.Format 方法的几种定义: String.Form ...
- c++中vector的用法详解
c++中vector的用法详解 vector(向量): C++中的一种数据结构,确切的说是一个类.它相当于一个动态的数组,当程序员无法知道自己需要的数组的规模多大时,用其来解决问题可以达到最大节约空间 ...
- php中setcookie函数用法详解(转)
php中setcookie函数用法详解: php手册中对setcookie函数讲解的不是很清楚,下面是我做的一些整理,欢迎提出意见. 语法: bool set ...
- JavaScript中return的用法详解
JavaScript中return的用法详解 最近,跟身边学前端的朋友了解,有很多人对函数中的this的用法和指向问题比较模糊,这里写一篇博客跟大家一起探讨一下this的用法和指向性问题. 1定义 t ...
- Mysql中limit的用法详解
Mysql中limit的用法详解 在我们使用查询语句的时候,经常要返回前几条或者中间某几行数据,为我们提供了limit这样一个功能. SELECT * FROM table LIMIT [offset ...
随机推荐
- TAT
瞎扯 继\(HNOI,\)学科\(,CTSC, APIO\)连续爆炸之后 曾一度的怀疑人生,没有任何搞学习的欲望 不断的反省自己:我为什么这么菜? 然后回去搞学科,一直处于一个颓废的状态 后来得知\( ...
- Chrome控制台毫无反应,打印不出信息了?
最近在使用console.log()方法的时候遇到一个奇怪的问题,打开chrome控制台想调试代码,结果控制台半天无反应,让我纳闷了半天.详情如图所示: 然后我又打开了新的标签页,不行!接着干脆关闭浏 ...
- Hibernate_Validator学习
1. Hibernate Validator介绍 1.1 背景 在任何时候,当你要处理一个应用程序的业务逻辑,数据校验是你必须要考虑和面对的事情.应用程序必须通过某种手段来确保输入进来的数据从 ...
- ubuntu16.0.4安装mysql5.7以及设置远程访问
1.安装mysql命令 sudo apt-get install mysql-server sudo apt install mysql-client sudo apt install libmysq ...
- Hadoop完全分布分布式配置
1.准备三台虚拟机.安装Ubuntu操作系统,具体过程省略 2.三台虚拟机上分别安装Java环境,具体过程省略(保证三者的Java路径一致) 3.三台机器分别配置ssh本机免密码登录 (1)安装ssh ...
- 微信小程序一个页面多个按钮分享怎么处理
首先呢,第一步先看api文档: 组件:button https://developers.weixin.qq.com/miniprogram/dev/component/button.html 框架- ...
- Protocol Buffer学习笔记
Protocol Buffer Protobuf基础概念 Protobuf是google开发的数据结构描述语言,能够将结构化数据序列化与反序列化,取代json和xml,常用于服务器通信协议.RPC系统 ...
- Azure 中部署Gitlab的方法
一.Azure 中创建Gitlab虚拟机(1).登陆Azure:打开Azure 官网,点击右侧上方的登陆Azure门户,输入Azure帐号与密码,点击 登陆 . (2).创建Gitlab虚拟机:登陆A ...
- MySql 时间处理
纸上得来终觉浅,绝知此事要躬行 博客园 首页 新闻 新随笔 联系 管理 随笔- 490 文章- 0 评论- 65 MySql 时间处理 这里是一个使用日期函数的例子.下面的查询选择了所有记录,其 ...
- 采用powershell创建project网站集(摘抄自https://www.cnblogs.com/jindahao/p/5855668.html)
采用powershell创建project网站集,具体步骤如下 1.输入License Enable-ProjectServerLicense –Key "23CB6-N4X8Q-WWD7M ...