C#中HttpWebRequest的用法详解
作者:shichen2014 发布时间:2023-06-18 22:39:27
本文实例讲述了C#中HttpWebRequest的用法。分享给大家供大家参考。具体如下:
HttpWebRequest类主要利用HTTP 协议和服务器交互,通常是通过 GET 和 POST 两种方式来对数据进行获取和提交。下面对这两种方式进行一下说明:
GET 方式:
GET 方式通过在网络地址附加参数来完成数据的提交,比如在地址 https://www.aspxhome.com/?hl=zh-CN 中,前面部分 https://www.aspxhome.com表示数据提交的网址,后面部分 hl=zh-CN 表示附加的参数,其中 hl 表示一个键(key), zh-CN 表示这个键对应的值(value)。
程序代码如下:
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "https://www.aspxhome.com?hl=zh-CN" );
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{
//在这里对接收到的页面内容进行处理
}
使用 GET 方式提交中文数据。
GET 方式通过在网络地址中附加参数来完成数据提交,对于中文的编码,常用的有 gb2312 和 utf8 两种。
用 gb2312 方式编码访问的程序代码如下:
Encoding myEncoding = Encoding.GetEncoding("gb2312");
string address = "https://www.aspxhome.com/?" + HttpUtility.UrlEncode("参数一", myEncoding) + "=" + HttpUtility.UrlEncode("值一", myEncoding);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address);
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{
//在这里对接收到的页面内容进行处理
}
在上面的程序代码中,我们以 GET 方式访问了网址 https://www.aspxhome.com ,传递了参数“参数一=值一”,由于无法告知对方提交数据的编码类型,所以编码方式要以对方的网站为标准。
POST 方式:
POST 方式通过在页面内容中填写参数的方法来完成数据的提交,参数的格式和 GET 方式一样,是类似于 hl=zh-CN&newwindow=1 这样的结构。
程序代码如下:
string param = "hl=zh-CN&newwindow=1";
byte[] bs = Encoding.ASCII.GetBytes(param);
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create( "https://www.aspxhome.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())
{
//在这里对接收到的页面内容进行处理
}
在上面的代码中,我们访问了 https://www.aspxhome.com 的网址,分别以 GET 和 POST 方式提交了数据,并接收了返回的页面内容。然而,如果提交的参数中含有中文,那么这样的处理是不够的,需要对其进行编码,让对方网站能够识别。
使用 POST 方式提交中文数据
POST 方式通过在页面内容中填写参数的方法来完成数据的提交,由于提交的参数中可以说明使用的编码方式,所以理论上能获得更大的兼容性。
用 gb2312 方式编码访问的程序代码如下:
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( "https://www.aspxhome.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 类的使用方法
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;
}
}
}
希望本文所述对大家的C#程序设计有所帮助。


猜你喜欢
- 利用属性动画实现优酷菜单,供大家参考,具体内容如下布局文件<RelativeLayout xmlns:android="ht
- 前言在使用Mybatis-Plus新增的时候,我们往往想要id随着数据库自增,但是如果不是我们指定id为auto(自增)的话,会通过算法算出
- 背景在实际开发过程中,会遇到需要编写各类打印模板模板的需求,当然这些在WPF开发中更为常见,但是使用XAML写编辑的打印模板又不能直接发送给
- 如下所示:# ===============================================================
- 可以使用 Intent.createChooser() 的方法来创建 Intent,并传入想要的 Sting 作为标题。 以wallpape
- 1. 经过简化的Property 早些时候我们这样声明Property private string _myName; public str
- 为了完成以上的需求,我们就需要模拟浏览器浏览网页,得到页面的数据在进行分析,最后把分析的结构,即整理好的数据写入数据库。那么我们的思路就是:
- 本文实例讲述了WinForm实现仿视频播放器左下角滚动新闻效果的方法。分享给大家供大家参考。具体实现方法如下:using System;us
- 最近看了一些淘宝购物车的demo,于是也写了一个。效果图如下:主要代码如下: actvity中的代码:public class Shoppi
- 其实这个http下载器的功能已经相当完善了,支持:限速、post投递和上传、自定义http header、设置user agent、设置ra
- 首先,定义TabHost的布局文件:<?xml version="1.0" encoding="utf-
- 尝试了各种防止中文乱码的方式,但是还是乱码;最后还是细节问题导致;解决方式:以及俩种方式是百度的,我的问题不是这俩块1.在requestMa
- 场景File与FileStream的区别举例:将读取文件比作是从A桶往B桶运水。使用File就是整个用桶倒进去,使用FileStream就是
- 前言本文章接上一篇文章继续谈一谈condition的一些用法。案例上一篇文章我提的一个需求时导入jedis坐标后才能加载该Bean,否则不加
- springboot jpa 延迟加载问题在springboot中,在application.properties的配置文件中新增sprin
- 什么是代理代理就是给目标对象一个代理对象,并由代理对象控制目标的引用。为什么要使用代理模式1、通过引入代理对象的方式,可以间接的访问目标对象
- 本文实例讲述了C#利用原图和水印图的重叠简单实现水印的方法。分享给大家供大家参考,具体如下:图片操作类/// <summary>
- 在项目中,有时候会用到领域枚举和DTO枚举的映射和转换。有一个现实的问题是:如果领域枚举项发生变化,而DTO枚举项没有及时更新,这样会造成映
- Unsafe类是啥?Java最初被设计为一种安全的受控环境。尽管如此,Java HotSpot还是包含了一个“后门”,提供了一些可以直接操控
- XListview是一个非常受欢迎的下拉刷新控件,但是已经停止维护了。之前写过一篇XListview的使用介绍,用起来非常简单,这两天放假无