HttpWebRequest类主要利用HTTP 协议和服务器交互,通常是通过 GET 和 POST 两种方式来对数据进行获取和提交。下面对这两种方式进行一下说明:

GET 方式

GET 方式通过在网络地址附加参数来完成数据的提交,比如在地址 http://www.studyofnet.com/?hl=zh-CN 中,前面部分 http://www.studyofnet.com表示数据提交的网址,后面部分 hl=zh-CN 表示附加的参数,其中 hl 表示一个键(key), zh-CN 表示这个键对应的值(value)。

程序代码如下:

C# 代码   复制

  HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.studyofnet.com?hl=zh-CN" );

req.Method = "GET";

using (WebResponse wr = req.GetResponse())

{
//在这里对接收到的页面内容进行处理
}

使用 GET 方式提交中文数据。

GET 方式通过在网络地址中附加参数来完成数据提交,对于中文的编码,常用的有 gb2312 和 utf8 两种。

用 gb2312 方式编码访问的程序代码如下:

 
C# 代码   复制

Encoding myEncoding = Encoding.GetEncoding("gb2312");

string address = "http://www.studyofnet.com/?" + HttpUtility.UrlEncode("参数一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding);

HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address);

req.Method = "GET";

using (WebResponse wr = req.GetResponse())

{
//在这里对接收到的页面内容进行处理
}

在上面的程序代码中,我们以 GET 方式访问了网址 http://www.studyofnet.com ,传递了参数“参数一=值一”,由于无法告知对方提交数据的编码类型,所以编码方式要以对方的网站为标准。

POST 方式

POST 方式通过在页面内容中填写参数的方法来完成数据的提交,参数的格式和 GET 方式一样,是类似于 hl=zh-CN&newwindow=1 这样的结构。

程序代码如下:

 
C# 代码   复制

string param = "hl=zh-CN&newwindow=1";

byte[] bs = Encoding.ASCII.GetBytes(param);

HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.studyofnet.com/" );

req.Method = "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())
{
//在这里对接收到的页面内容进行处理
}

在上面的代码中,我们访问了 http://www.studyofnet.com 的网址,分别以 GET 和 POST 方式提交了数据,并接收了返回的页面内容。然而,如果提交的参数中含有中文,那么这样的处理是不够的,需要对其进行编码,让对方网站能够识别。

使用 POST 方式提交中文数据

POST 方式通过在页面内容中填写参数的方法来完成数据的提交,由于提交的参数中可以说明使用的编码方式,所以理论上能获得更大的兼容性。

用 gb2312 方式编码访问的程序代码如下:

C# 代码   复制

 Encoding myEncoding = Encoding.GetEncoding("gb2312");

string param = HttpUtility.UrlEncode("参数一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding) + "&" + HttpUtility.UrlEncode("参数二", myEncoding) + "=" + HttpUtility.UrlEncode("值二", myEncoding);

byte[] postBytes = Encoding.ASCII.GetBytes(param);

HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "http://www.studyofnet.com/" );

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 码,然后提交到服务器,提交的时候可以说明编码的方式,用来使对方服务器能够正确的解析。

用C#语言写的关于HttpWebRequest 类的使用方法

 
C# 代码   复制

using System;

using System.Collections.Generic;

using System.IO;

using System.Net;

using System.Text;

namespace HttpWeb

{
/// <summary>
/// Http操作类
/// </summary>
public static class httptest
{
/// <summary>
/// 获取网址HTML
/// </summary>
/// <param name="URL">网址 </param>
/// <returns> </returns>
public static string GetHtml(string URL)
{
WebRequest wrt;
wrt = WebRequest.Create(URL);
wrt.Credentials = CredentialCache.DefaultCredentials;
WebResponse wrp;
wrp = wrt.GetResponse();
string reader = new StreamReader(wrp.GetResponseStream(), Encoding.GetEncoding("gb2312")).ReadToEnd();
try
{
wrt.GetResponse().Close();
}
catch (WebException ex)
{
throw ex;
}
return reader;
}
/// <summary>
/// 获取网站cookie
/// </summary>
/// <param name="URL">网址 </param>
/// <param name="cookie">cookie </param>
/// <returns> </returns>
public static string GetHtml(string URL, out string cookie)
{
WebRequest wrt;
wrt = WebRequest.Create(URL);
wrt.Credentials = CredentialCache.DefaultCredentials;
WebResponse wrp;

wrp = wrt.GetResponse();


string html = new StreamReader(wrp.GetResponseStream(), Encoding.GetEncoding("gb2312")).ReadToEnd();

try
{
wrt.GetResponse().Close();
}
catch (WebException ex)
{
throw ex;
}

cookie = wrp.Headers.Get("Set-Cookie");
return html;
}
public static string GetHtml(string URL, string postData, string cookie, out string header, string server)
{
return GetHtml(server, URL, postData, cookie, out header);
}
public static string GetHtml(string server, string URL, string postData, string cookie, out string header)
{
byte[] byteRequest = Encoding.GetEncoding("gb2312").GetBytes(postData);
return GetHtml(server, URL, byteRequest, cookie, out header);
}
public static string GetHtml(string server, string URL, byte[] byteRequest, string cookie, out string header)
{
byte[] bytes = GetHtmlByBytes(server, URL, byteRequest, cookie, out header);
Stream getStream = new MemoryStream(bytes);
StreamReader streamReader = new StreamReader(getStream, Encoding.GetEncoding("gb2312"));
string getString = streamReader.ReadToEnd();
streamReader.Close();
getStream.Close();
return getString;
}

/// <summary>
/// Post模式浏览
/// </summary>
/// <param name="server">服务器地址 </param>
/// <param name="URL">网址 </param>
/// <param name="byteRequest">流 </param>
/// <param name="cookie">cookie </param>
/// <param name="header">句柄 </param>
/// <returns> </returns>
public static byte[] GetHtmlByBytes(string server, string URL, byte[] byteRequest, string cookie, out string header)
{
long contentLength;
HttpWebRequest httpWebRequest;
HttpWebResponse webResponse;
Stream getStream;

httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL);
CookieContainer co = new CookieContainer();
co.SetCookies(new Uri(server), cookie);

httpWebRequest.CookieContainer = co;

httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Accept =
"image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
httpWebRequest.Referer = server;
httpWebRequest.UserAgent =
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";
httpWebRequest.Method = "Post";
httpWebRequest.ContentLength = byteRequest.Length;
Stream stream;
stream = httpWebRequest.GetRequestStream();
stream.Write(byteRequest, 0, byteRequest.Length);
stream.Close();
webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
header = webResponse.Headers.ToString();
getStream = webResponse.GetResponseStream();
contentLength = webResponse.ContentLength;

byte[] outBytes = new byte[contentLength];
outBytes = ReadFully(getStream);
getStream.Close();
return outBytes;
}
public static byte[] ReadFully(Stream stream)
{
byte[] buffer = new byte[128];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}

/// <summary>
/// Get模式
/// </summary>
/// <param name="URL">网址 </param>
/// <param name="cookie">cookies </param>
/// <param name="header">句柄 </param>
/// <param name="server">服务器 </param>
/// <param name="val">服务器 </param>
/// <returns> </returns>
public static string GetHtml(string URL, string cookie, out string header, string server)
{
return GetHtml(URL, cookie, out header, server, "");
}
/// <summary>
/// Get模式浏览
/// </summary>
/// <param name="URL">Get网址 </param>
/// <param name="cookie">cookie </param>
/// <param name="header">句柄 </param>
/// <param name="server">服务器地址 </param>
/// <param name="val"> </param>
/// <returns> </returns>
public static string GetHtml(string URL, string cookie, out string header, string server, string val)
{
HttpWebRequest httpWebRequest;
HttpWebResponse webResponse;
Stream getStream;
StreamReader streamReader;
string getString = "";
httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(URL);
httpWebRequest.Accept = "*/*";
httpWebRequest.Referer = server;
CookieContainer co = new CookieContainer();
co.SetCookies(new Uri(server), cookie);
httpWebRequest.CookieContainer = co;
httpWebRequest.UserAgent =
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";
httpWebRequest.Method = "GET";
webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
header = webResponse.Headers.ToString();
getStream = webResponse.GetResponseStream();
streamReader = new StreamReader(getStream, Encoding.GetEncoding("gb2312"));
getString = streamReader.ReadToEnd();

streamReader.Close();
getStream.Close();
return getString;
}
}
}

HttpWebRequest的使用的更多相关文章

  1. 利用HttpWebRequest实现实体对象的上传

    一 简介 HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数据的最好选择.它们支持一系列有用的属性.这两个类位 于System.Net命名空间,默认情况下这个类对 ...

  2. C#通过WebClient/HttpWebRequest实现http的post/get方法

    C#通过WebClient/HttpWebRequest实现http的post/get方法 http://www.cnblogs.com/shadowtale/p/3372735.html

  3. C# HttpWebRequest获取COOKIES

    C# HttpWebRequest获取COOKIES byte[] bytes = Encoding.Default.GetBytes(_post); CookieContainer myCookie ...

  4. 在使用 HttpWebRequest Post数据时候返回 400错误

    笔者有一个项目中用到了上传zip并解压的功能.开始觉得很简单,因为之前曾经做过之类的上传文件的功能,所以并不为意,于是使用copy大法.正如你所料,如果一切很正常的能运行的话就不会有这篇笔记了. 整个 ...

  5. .net学习笔记----HttpRequest,WebRequest,HttpWebRequest区别

    WebRequest是一个虚类/基类,HttpWebRequest是WebRequest的具体实现 HttpRequest类的对象用于服务器端,获取客户端传来的请求的信息,包括HTTP报文传送过来的所 ...

  6. C#使用HttpWebRequest 进行请求,提示 基础连接已经关闭: 发送时发生错误。

    本人今天遇到的错误,C#使用HttpWebRequest 进行请求,提示 基础连接已经关闭: 发送时发生错误. 测试了很久,才发现,是安全协议问题,把安全协议加上就可以了

  7. C# winfrom HttpWebRequest 请求获取html网页信息和提交信息

    string result =GetRequest("http://localhost:32163/DuoBao/ajax.aspx", "time=5"); ...

  8. ASP.NET中使用HttpWebRequest调用WCF

    最近项目需要和第三网站进行数据交换,第三方网站基本都是RESTfull形式的API,但是也有的是Web Service,或者.NET里面的WCF.微软鼓励大家使用WCF替代Web Service. W ...

  9. 【转】asp.net(c#)使用HttpWebRequest附加携带请求参数以post方式模拟上传大文件(以图片为例)到Web服务器端

    原文地址:http://docode.top/Article/Detail/10002 目录: 1.Http协议上传文件(以图片为例)请求报文体内容格式 2.完整版HttpWebRequest模拟上传 ...

  10. .Net(c#)模拟Http请求之HttpWebRequest封装

    一.需求: 向某个服务发起请求获取数据,如:爬虫,采集. 二.步骤(HttpWebRequest): 无非在客户端Client(即程序)设置请求报文(如:Method,Content-Type,Age ...

随机推荐

  1. Swift2.0语言教程之类的属性

    Swift2.0语言教程之类的属性 类 虽然函数可以简化代码,但是当一个程序中出现成百上千的函数和变量时,代码还是会显得很混乱.为此,人们又引入了新的类型——类.它是人们构建代码所用的一种通用.灵活的 ...

  2. requests https访问错误SSLError: certificate verify failed 及InsecureRequestWarning处理办法

    转自: https://blog.csdn.net/mighty13/article/details/78076258?locationNum=3&fps=1 在使用requests访问某网站 ...

  3. 为什么全部width:100%浏览器边缘存在留白?

    一般浏览器都给body加了外边距,margin:0应该能解决你所遇到的问题.但你很可能又会遇到其他奇怪的现象,比如说p的行高,在不同浏览器上显示不一致,最根本的解决方案还是重置浏览器默认样式. 可以使 ...

  4. CF912D Fishes 期望 + 贪心

    有趣的水题 由期望的线性性质,全局期望 = 每个格子的期望之和 由于权值一样,我们优先选概率大的点就好了 用一些数据结构来维护就好了 复杂度$O(k \log n)$ #include <set ...

  5. BZOJ 4003: [JLOI2015]城池攻占 左偏树 可并堆

    https://www.lydsy.com/JudgeOnline/problem.php?id=4003 感觉就是……普通的堆啊(暴论),因为这个堆是通过递归往右堆里加一个新堆或者新节点的,所以要始 ...

  6. 【推导】The 16th UESTC Programming Contest Preliminary L - Foxtrot

    题意:有n瓶药剂,其中只有一瓶药剂有毒.让你用最少的小白鼠试出哪瓶有毒.你只有一次给任意只小白鼠各喂食任意种类药剂的机会. m只老鼠就能对应2^m种“生死状态”的组合,给每种状态分配一个种类的药剂,然 ...

  7. 2018-2019-2 20162318《网络对抗技术》Exp2 后门原理与实践

    一.实验内容 1.使用netcat获取主机操作Shell,cron启动 2.使用socat获取主机操作Shell, 任务计划启动 3.使用MSF meterpreter(或其他软件)生成可执行文件,利 ...

  8. poj 2777 线段树 区间更新+位运算

    题意:有一个长板子,分成多段,有两种操作,第一种是C给从a到b那段染一种颜色c,另一种是P询问a到b有多少种不同的颜色.Sample Input2 2 4  板长 颜色数目 询问数目C 1 1 2P ...

  9. C#高级编程9-第5章 泛型

    泛型 1.泛型概述 泛型是C#的部分与中间语言IL集成.创建的类或方法指定了类型,在实例化和调用时必须指定类型进行操作. 泛型可以用于类.方法.接口和委托以及结构. 泛型也是结构,同时是运行库CLR定 ...

  10. Windows下ftp服务器搭建及配置

    Win系统使用ser-u软件进行FTP服务器的搭建下载地址:https://www.serv-u.com/操作步骤如下:1. 点击执行程序进行按照SU-FTP-Server-Windows-v15.1 ...