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提交数据⽅式:
HttpWebRequest req =
(HttpWebRequest)HttpWebRequest.Create("le/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("le/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())
{
//在这⾥对接收到的页⾯内容进⾏处理
}
3. 使⽤ GET ⽅式提交中⽂数据。
GET ⽅式通过在⽹络地址中附加参数来完成数据提交,对于中⽂的编码,常⽤的有 gb2312 和 utf8 两种,⽤ gb2312 ⽅式编码访问的程序代码如下:
Encoding myEncoding = Encoding.GetEncoding("gb2312");    //确定⽤哪种中⽂编码⽅式
string address = "www.baidu/s?"+ HttpUtility.UrlEncode("参数⼀", myEncoding) +  "=" + HttpUtility.UrlEncode("值⼀", myEncoding);      //拼接数据提交的⽹址和经过中⽂编码后的中⽂参数
HttpWebRequest req =  (HttpWebRequest)HttpWebRequest.Create(address);  //创建request
req.Method = "GET";    //确定传值⽅式,此处为get⽅式
using (WebResponse wr = req.GetResponse())
{
//在这⾥对接收到的页⾯内容进⾏处理
}
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( "www.baidu/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 码,然后提交到服务器,提交的时候可以说明编码的⽅式,⽤来使
对⽅服务器能够正确的解析。
以上列出了客户端程序使⽤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, 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
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 = 20000;
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();
httpWebRequest.Abort();
httpWebResponse.Close();
return responseContent;
}
2.POST⽅法(WebClient)
///<summary>
///通过WebClient类Post数据到远程地址,需要Basic认证;
///调⽤端⾃⼰处理异常
///</summary>
web端登录///<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(0, queryString.Length - 1);
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + queryString);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
httpWebRequest.Timeout = 20000;
//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 > 0)
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

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。