发送HTTP请求


 

前言

最近一直在做C# winform客户端项目,因为涉及到和服务器交互,所以研究了一下C#的HTTP网络编程。

Http通信是通过Http请求报文和Http应答报文来实现的。

由于我开发的是客户端,所以主要工作就在于封装Http请求报文,以及收到应答报文后解析数据。


Http请求报文是什么样的

如果你使用的是chrome浏览器,按F12就可以开启调试模式。现在主流的浏览器应该都支持这个功能。随便打开一个网页,触发一个超链接请求,应该就能抓取到Http请求报文。

举个例子,以下是一个Http请求报文的截取内容。

我们可以看到请求报文中有很多参数,这里不一一详解各个参数的意义。

 


C#中实现Http请求

我个人认为,发送Http请求报文主要有四个步骤

1.       初始化HttpWebRequest(需要引用System.Net)

2.       封装Http cookie

3.       封装Http报文头

4.       封装请求内容,并将封装好的请求报文用Stream类写入流(需要引用System.IO

5.       接收应答报文

接下来,我们一步一步来讲解如何在C#中完成Http请求报文的封装。

初始化HttpWebRequest

使用请求地址作为参数,初始化一个HttpWebRequest实例。

// 初始化HttpWebRequest
HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(strRequestUri);

 

封装Http cookie

首先,简单说明一下Cookie。有时也用其复数形式Cookies,指某些网站为了辨别用户身份、进行session跟踪而储存在用户本地终端上的数据(通常经过加密)。本文为了示例,就以比较简单的形式展现。

在C#中,使用Cookie类来封装cookie,以键值对的形式保存。

然后,将这个封装好的cookie添加到CookieContainer容器中,最后填入HttpWebRequest。既然是容器,顾名思义,可以添加多个cookie。

// 封装Cookie
Uri uri = new Uri(strRequestUri);

Cookie cookie = new Cookie("Name", strCookie); // 设置key、value形式的Cookie
CookieContainer cookies = new CookieContainer();

cookies.Add(uri, cookie);
httpRequest.CookieContainer = cookies;


封装Http Header

根据自己要发送的请求报文类型来填充Http报文头。

以下是一个简单范例:

复制代码
// 封装Http Header
httpRequest.Method = "Post";

httpRequest.Referer = strReferer;
httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.89 Safari/537.36";
httpRequest.Accept = "text/plain, */*; q=0.01";
httpRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
httpRequest.Timeout = 1000 * 30;
httpRequest.KeepAlive = true;
复制代码

 

填充Http content,并写入流

首先,将要写入的内容转为byte数组(假设是文本内容)。将数组长度填入HttpWebRequest的ContentLength字段。

通过GetRequestStream()获取HttpWebRequest的请求流。使用这个流对象写入数组内容。

最后,千万不要忘记关闭流。本人在开发C#客户端和Java服务器交互过程中,就遇到这个问题。由于忘记关闭流,Java服务器在解析请求报文时,总是提示不能识别流的结尾。

// 通过流写入请求数据
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strContent); // 编码形式按照个人需求来设置
httpRequest.ContentLength = bytes.Length;

Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close(); // 不要忘记关闭流

 

获得应答报文

通过流将请求报文发出去后,可以通过HttpWebRequest的GetResponse()方法来获取HttpWebResponse

// 获得应答报文
HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();

Stream responseStream = httpResponse.GetResponseStream();
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
string strResponse = reader.ReadToEnd();
reader.Close();
responseStream.Close();

至此,Http请求过程结束。大家有疑问的地方,欢迎和我探讨。

过两天,我再整理一下上传文件的 Http方法。

 

附上完整方法

复制代码
public static void PackageHttpRequest(string strRequestUri, string strReferer, string strContent, string strCookie)
{
    // 初始化HttpWebRequest
    HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(strRequestUri);


    // 封装Cookie
    Uri uri = new Uri(strRequestUri);

    Cookie cookie = new Cookie("Name", strCookie); // 设置key、value形式的Cookie
    CookieContainer cookies = new CookieContainer();

    cookies.Add(uri, cookie);
    httpRequest.CookieContainer = cookies;

    // 封装Http Header
    httpRequest.Method = "Post";

    httpRequest.Referer = strReferer;
    httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.89 Safari/537.36";
    httpRequest.Accept = "text/plain, */*; q=0.01";
    httpRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
    httpRequest.Timeout = 1000 * 30;
    httpRequest.KeepAlive = true;

    // 通过流写入请求数据
    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strContent); // 编码形式按照个人需求来设置
    httpRequest.ContentLength = bytes.Length;

    Stream requestStream = httpRequest.GetRequestStream();
    requestStream.Write(bytes, 0, bytes.Length);
    requestStream.Close(); // 不要忘记关闭流

    
// 获得应答报文
    HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();

    Stream responseStream = httpResponse.GetResponseStream();
    StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
    string strResponse = reader.ReadToEnd();
    reader.Close();
    responseStream.Close();
}
复制代码


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM