HttpWebRequest类

news2024/9/30 13:33:17

HttpWebRequest类与HttpRequest类的区别。

HttpRequest类的对象用于服务器端,获取客户端传来的请求的信息,包括HTTP报文传送过来的所有信息。而HttpWebRequest用于客户端,拼接请求的HTTP报文并发送等。

HttpWebRequest这个类非常强大,强大的地方在于它封装了几乎HTTP请求报文里需要用到的东西,以致于能够能够发送任意的HTTP请求并获得服务器响应(Response)信息。采集信息常用到这个类。在学习这个类之前,首先有必要了解下HTTP方面的知识。

一、简单示例
  我们先来一个最简单的,就是紧紧输入一个网址就获取响应。代码如下:

复制代码
class Program
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(“http://www.baidu.com”); //创建一个请求示例
HttpWebResponse response = (HttpWebResponse)request.GetResponse();  //获取响应,即发送请求
Stream responseStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
string html = streamReader.ReadToEnd();
Console.WriteLine(html);

        Console.ReadKey();
    }
}

复制代码
  OK,就是这么简单了,真的这么简单吗?发送一个HTTP请求真的这么简单。但是要做出很多功能就不简单了。你需要详细了解下HTTP方面的知识,比如HTTP请求报文之类的。

二、模拟登录
  下面来个复杂点的,这次是获取登录之后的页面。登录之后的请求用什么实现呢?呵呵,用到是cookie。在拼接HTTP请求的时候,连着cookie也发送过去。

复制代码
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
HttpHeader header = new HttpHeader();
header.accept = “image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, /”;
header.contentType = “application/x-www-form-urlencoded”;
header.method = “POST”;
header.userAgent = “Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)”;
header.maxTry = 300;

        //在这里自己拼接一下Cookie,不用复制过来的那个GetCookie方法了,原来的那个写法还是比较严谨的
        CookieContainer cc = new CookieContainer();
        Cookie cUserName = new Cookie("cSpaceUserEmail", "742783833%40qq.com");
        cUserName.Domain = ".7soyo.com";
        Cookie cUserPassword = new Cookie("cSpaceUserPassWord", "4f270b36a4d3e5ee70b65b1778e8f793");
        cUserPassword.Domain = ".7soyo.com";
        cc.Add(cUserName);
        cc.Add(cUserPassword);

        string html = HTMLHelper.GetHtml("http://user.7soyo.com/CollectUser/List", cc, header);
        FileStream fs = new FileStream(@"D:\123.txt",FileMode.CreateNew,FileAccess.ReadWrite);
        fs.Write(Encoding.UTF8.GetBytes(html),0,html.Length);
        fs.Flush();
        fs.Dispose();

        Console.WriteLine(html);

        Console.ReadKey();
    }
}

public class HTMLHelper
{
    /// <summary>
    /// 获取CooKie
    /// </summary>
    /// <param name="loginUrl"></param>
    /// <param name="postdata"></param>
    /// <param name="header"></param>
    /// <returns></returns>
    public static CookieContainer GetCooKie(string loginUrl, string postdata, HttpHeader header)
    {
        HttpWebRequest request = null;
        HttpWebResponse response = null;
        try
        {
            CookieContainer cc = new CookieContainer();
            request = (HttpWebRequest)WebRequest.Create(loginUrl);
            request.Method = header.method;
            request.ContentType = header.contentType;
            byte[] postdatabyte = Encoding.UTF8.GetBytes(postdata);     //提交的请求主体的内容
            request.ContentLength = postdatabyte.Length;    //提交的请求主体的长度
            request.AllowAutoRedirect = false;
            request.CookieContainer = cc;
            request.KeepAlive = true;

            //提交请求
            Stream stream;
            stream = request.GetRequestStream();
            stream.Write(postdatabyte, 0, postdatabyte.Length);     //带上请求主体
            stream.Close();

            //接收响应
            response = (HttpWebResponse)request.GetResponse();      //正式发起请求
            response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);

            CookieCollection cook = response.Cookies;
            //Cookie字符串格式
            string strcrook = request.CookieContainer.GetCookieHeader(request.RequestUri);

            return cc;
        }
        catch (Exception ex)
        {

            throw ex;
        }
    }

    /// <summary>
    /// 获取html
    /// </summary>
    /// <param name="getUrl"></param>
    /// <param name="cookieContainer"></param>
    /// <param name="header"></param>
    /// <returns></returns>
    public static string GetHtml(string getUrl, CookieContainer cookieContainer, HttpHeader header)
    {
        Thread.Sleep(1000);
        HttpWebRequest httpWebRequest = null;
        HttpWebResponse httpWebResponse = null;
        try
        {
            httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(getUrl);
            httpWebRequest.CookieContainer = cookieContainer;
            httpWebRequest.ContentType = header.contentType;
            httpWebRequest.ServicePoint.ConnectionLimit = header.maxTry;
            httpWebRequest.Referer = getUrl;
            httpWebRequest.Accept = header.accept;
            httpWebRequest.UserAgent = header.userAgent;
            httpWebRequest.Method = "GET";
            httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            Stream responseStream = httpWebResponse.GetResponseStream();
            StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
            string html = streamReader.ReadToEnd();
            streamReader.Close();
            responseStream.Close();
            httpWebRequest.Abort();
            httpWebResponse.Close();
            return html;
        }
        catch (Exception e)
        {
            if (httpWebRequest != null) httpWebRequest.Abort();
            if (httpWebResponse != null) httpWebResponse.Close();
            return string.Empty;
        }
    }
}

public class HttpHeader
{
    public string contentType { get; set; }

    public string accept { get; set; }

    public string userAgent { get; set; }

    public string method { get; set; }

    public int maxTry { get; set; }
}

}
复制代码
  这样获取到的就是登录之后的页面了。

三、模拟表单提交
  再来一个例子,运用HttpWebRequest来模拟表单的提交,先新建一个MVC项目,里面只有这些代码:

复制代码
[HttpPost]
public ActionResult Index(string userName,string userPassword)
{
string str = “你提交过来的用户名是:” + userName + ",密码是: " + userPassword;
Response.Write(str);
return View();
}
复制代码
  然后启动该项目,再新建另外一个项目,用于模拟提交表单,然后注意路径填写的是刚才建的那个MVC项目。

复制代码
static void Main(string[] args)
{
HttpWebRequest request = null;
HttpWebResponse response = null;
CookieContainer cc = new CookieContainer();
request = (HttpWebRequest)WebRequest.Create(“http://localhost:2539/”);
request.Method = “POST”;
request.ContentType = “application/x-www-form-urlencoded”;
request.UserAgent = “Mozilla/5.0 (Windows NT 6.1; rv:19.0) Gecko/20100101 Firefox/19.0”;

        string requestForm = "userName=1693372175&userPassword=123456";     //拼接Form表单里的信息
        byte[] postdatabyte = Encoding.UTF8.GetBytes(requestForm);
        request.ContentLength = postdatabyte.Length;
        request.AllowAutoRedirect = false;
        request.CookieContainer = cc;
        request.KeepAlive = true;

        Stream stream;
        stream = request.GetRequestStream();
        stream.Write(postdatabyte, 0, postdatabyte.Length); //设置请求主体的内容
        stream.Close();

        //接收响应
        response = (HttpWebResponse)request.GetResponse();
        Console.WriteLine();

        Stream stream1 = response.GetResponseStream();
        StreamReader sr = new StreamReader(stream1);
        Console.WriteLine(sr.ReadToEnd());
    
        Console.ReadKey();
    }

复制代码
  输出结果如下所示:

四、模拟上传
  血的教训,注意路径不能写错,否则在对流进行操作时,Write,就会报错:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(“http://localhost:9170/upload/test”);
  客户端:

复制代码
class Program
{
/**
* 如果要在客户端向服务器上传文件,我们就必须模拟一个POST multipart/form-data类型的请求
* Content-Type必须是multipart/form-data。
* 以multipart/form-data编码的POST请求格式与application/x-www-form-urlencoded完全不同
* multipart/form-data需要首先在HTTP请求头设置一个分隔符,例如7d4a6d158c9:
* 我们模拟的提交要设定 content-type不同于非含附件的post时候的content-type
* 这里需要: (“Content-Type”, “multipart/form-data; boundary=ABCD”);
* 然后,将每个字段用“–7d4a6d158c9”分隔,最后一个“–7d4a6d158c9–”表示结束。
* 例如,要上传一个title字段"Today"和一个文件C:\1.txt,HTTP正文如下:
*
* --7d4a6d158c9
* Content-Disposition: form-data; name=“title”
* \r\n\r\n
* Today
* --7d4a6d158c9
* Content-Disposition: form-data; name=“1.txt”; filename=“C:\1.txt”
* Content-Type: text/plain
* 如果是图片Content-Type: application/octet-stream
* \r\n\r\n
* <这里是1.txt文件的内容>
* --7d4a6d158c9
* \r\n
* 请注意,每一行都必须以\r\n结束value前面必须有2个\r\n,包括最后一行。
*/
static void Main(string[] args)
{
string boundary = “----------” + DateTime.Now.Ticks.ToString(“x”);//元素分割标记
StringBuilder sb = new StringBuilder();
sb.Append(“–” + boundary);
sb.Append(“\r\n”);
sb.Append(“Content-Disposition: form-data; name=“file1”; filename=“D:\upload.xml” + “””);
sb.Append(“\r\n”);
sb.Append(“Content-Type: application/octet-stream”);
sb.Append(“\r\n”);
sb.Append(“\r\n”);//value前面必须有2个换行

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:9170/upload/test");
        request.ContentType = "multipart/form-data; boundary=" + boundary;//其他地方的boundary要比这里多--  
        request.Method = "POST";

        FileStream fileStream = new FileStream(@"D:\123.xml", FileMode.OpenOrCreate, FileAccess.Read);

        byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sb.ToString());
        byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
        //http请求总长度  
        request.ContentLength = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
        Stream requestStream = request.GetRequestStream(); 
        requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
        byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
        int bytesRead = 0;
        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            requestStream.Write(buffer, 0, bytesRead);
        }
        fileStream.Dispose();
        requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
        WebResponse webResponse2 = request.GetResponse();
        Stream htmlStream = webResponse2.GetResponseStream();
        string HTML = GetHtml(htmlStream, "UTF-8");
        Console.WriteLine(HTML);
        htmlStream.Dispose();
    }

}
复制代码
  测试服务器端地址:

复制代码
public ActionResult Test()
{
HttpRequest request = System.Web.HttpContext.Current.Request;
HttpFileCollection FileCollect = request.Files;
if (FileCollect.Count > 0) //如果集合的数量大于0
{
foreach (string str in FileCollect)
{
HttpPostedFile FileSave = FileCollect[str]; //用key获取单个文件对象HttpPostedFile
string imgName = DateTime.Now.ToString(“yyyyMMddhhmmss”);
string AbsolutePath = FileSave.FileName;
FileSave.SaveAs(AbsolutePath); //将上传的东西保存
}
}
return Content(“键值对数目:” + FileCollect.Count);
}请添加图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/437963.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Spring MVC 接收 json 和返回 json (14)

目录 总入口 测试case 源码分析 1. 针对RequestBody的参数解析 2. 针对 ResponseBody 的返回值处理 总入口 通过上一篇Spring MVC 参数解析&#xff08;13&#xff09;_chen_yao_kerr的博客-CSDN博客的说明&#xff0c;相信大家对Sping MVC的参数解析有了一定的了解&…

2.微服务项目实战---环境搭建,实现电商中商品、订单、用户

使用的电商项目中的商品、订单、用户为案例进行讲解。 2.1 案例准备 2.1.1 技术选型 maven &#xff1a; 3.3.9 数据库&#xff1a; MySQL 5.7 持久层 : SpingData Jpa 其他 : SpringCloud Alibaba 技术栈 2.1.2 模块设计 springcloud-alibaba 父工程 shop-common …

【观察】构建“零信任”架构,筑起制造业安全“护城河”

中国是全球制造业大国&#xff0c;过去40年&#xff0c;中国制造业规模增长了18倍&#xff0c;其附加值达到2.2万亿美元&#xff0c;制造业在中国GDP比重高达40%&#xff0c;其之于中国经济的重要性可见一斑。 与此同时&#xff0c;中国制造业在高速发展的同时&#xff0c;也普…

使用全球融合CDN的10大优势

根据预估&#xff0c;今年的全球内容交付网络&#xff08;CDN&#xff09;市场预计将达到424亿美元。而由于移动应用程序的激增和人工智能尤其是ChatGPT等相关领域的快速发展将进一步带来CDN市场的快速增长&#xff0c;可以说全球CDN的黄金时代才刚开始。 融合CDN和多CDN战略是…

32道子网划分练习题详细解析含答案

目录 1 子网划分概念&#xff1a; 2 划分方法&#xff1a; 子网划分方法&#xff1a;段&#xff0c;块&#xff0c;数的计算三步。 段就是确定ip地址段中既有网络地址&#xff0c;又有主机地址的那一段是四段中的那一段&#xff1f; 块就确定上一步中确定的那一段中的主机…

企业云成本优化:减少企业云支出的终极指南

向云的转移使企业的技术领导者能够实现基础设施的现代化&#xff0c;并提高应用程序的可用性、可扩展性和性能。然而优化云成本对很多以互联网业务为主体的公司都是一项挑战&#xff0c;因为需要执行可持续的云成本管理战略。随着世界经济近年来走向低迷&#xff0c;尤其是互联…

【Linux网络服务】DNS域名解析服务服务

一、BIND域名服务基础 服务背景 1在日常生活中人们习惯使用域名访问服务器&#xff0c;但机器向互相只认IP地址&#xff0c;域名与IP地址之间是多对一的关系&#xff0c;一个IP址不一定只对应一个域名&#xff0c;且一个完成域名只可以对应一个IP地址&#xff0c;它们之间转换…

[ARM+Linux] 基于wiringPi库的串口通信

wiringOP-master/examples/serialTest.c中&#xff0c;wiringPi库中自带的串口程序&#xff1a; #include <stdio.h> #include <string.h> #include <errno.h>#include <wiringPi.h> #include <wiringSerial.h>int main () {int fd ;int count …

JavaSE-part1

文章目录 Day01 面向对象特性1.java继承注意点2.多态2.1多态概述2.2多态中成员的特点:star::star:2.3多态的转型:star::star: 3.Super4.方法重写:star::star:5.Object类:star::star: Day02 面向对象特性1.代码块:star:(主要是初始化变量&#xff0c;先于构造器)2.单例设计模式:…

服务器初始化

Linux基础系类 提示&#xff1a;个人学习总结&#xff0c;仅供参考。 一、Linux系统部署 二、服务器初始化 提示&#xff1a;文档陆续更新整理 服务器初始化 Linux基础系类简介一、配置IP地址二、配置YUM源&#xff08;yum本地源和yum网络源&#xff09;1.简介2.准备工作3.配置…

数据结构与算法——深度寻路算法

&#x1f4d6;作者介绍&#xff1a;22级树莓人&#xff08;计算机专业&#xff09;&#xff0c;热爱编程&#xff1c;目前在c&#xff0b;&#xff0b;阶段&#xff0c;因为最近参加新星计划算法赛道(白佬)&#xff0c;所以加快了脚步&#xff0c;果然急迫感会增加动力>——…

SQL Server的行级安全性

行级安全性 一、前言二、描述三、权限四、安全说明&#xff1a;侧信道攻击五、跨功能兼容性六、示例 一、前言 行级别安全性使您能够使用组成员身份或执行上下文来控制对数据库表中行的访问。 行级别安全性 &#xff08;RLS&#xff09; 简化了应用程序中的安全性设计和编码。…

MyBatis(一)

一、简介 1.1 什么是MyBatis MyBatis是一个持久层框架&#xff0c;既然和持久层有关那就可以简单理解成和数据库有关&#xff0c;既然是框架那么就肯定是为了简化数据库有关的操作。由于传统的JDBC代码处理数据库有关的代码太复杂&#xff0c;所以出现了MyBatis来快速处理数据…

RK3588调试CAN驱动记录

背景 汽车芯片公司&#xff0c;IP领导随机分配&#xff0c;主要任务是各种IP的硅前验证&#xff0c;包括uboot命令行和Linux kernel验证。工作两年半没什么外设经验也没做过CAN总线(前两年在一家芯片公司做各种加解密IP的开发)&#xff0c;一个人的摸索过程可以说是充满了坎坷…

花有约,春不迟|弘博创新2023塘朗山到梅林水库穿越活动

花有约,春不迟|弘博创新2023塘朗山到梅林水库穿越活动 花开有约&#xff0c;春日不迟 4月16日&#xff0c;正值春暖花开的季节&#xff0c;周末闲暇无事&#xff0c;弘博创新的朋友们相聚一起&#xff0c;从塘朗山龙珠门到梅林水库&#xff0c;体验一场感受大自然&#xff0c;开…

dsl语法

查询 1.查询所有&#xff08;默认有分页查询&#xff09; #查询所有 GET /hotel/_search {"query": {"match_all": {}} } 2.match查询&#xff08;条件查询&#xff09;-----包含四川和外滩的信息&#xff0c;信息匹配度越高越靠前&#xff0c;两者存在一…

知识库管理系统对于企业有哪些作用及优势?

知识库管理系统是一种通过集成多种技术手段&#xff0c;将企业内部知识进行收集、整理、存储、分析和共享的信息管理系统。知识库管理系统可以帮助企业管理和利用企业内部的知识&#xff0c;提高企业的创新能力和竞争力。 知识库管理系统的作用 1、促进企业内部知识的流通和共…

AutoGPT 安装指南,使用避坑要点

最近&#xff0c; AIGC 中最火的可能就当属于 AutoGPT 了吧&#xff0c;首先简单介绍一下AutoGPT 背景 AutoGPT 是基于 ChatGPT API 接口开发&#xff0c;项目首推 GPT-4 模型&#xff0c;但 OpenAI 账号 API 只有 gpt-3.5-turo 权限同样也可以使用。 项目在 github 上获取的…

Java多线程初阶(二)(图片+源码+超详细)

在这之前可以参照&#xff1a;Java多线程初阶&#xff08;一&#xff09;这篇文章&#x1f43b; 目录 1. 线程的状态 2. 线程安全问题 2.1 引出线程安全问题 2.2 线程安全问题出现的原因 2.3 解决线程安全问题的方法 2.4 synchronized关键字详解 2.5 volatile关键字详解…

【LeetCode】145.二叉树的后续遍历

1.问题 给你一棵二叉树的根节点 root &#xff0c;返回其节点值的 后序 遍历 。 示例 1&#xff1a; 输入&#xff1a;root [1,null,2,3] 输出&#xff1a;[3,2,1] 示例 2&#xff1a; 输入&#xff1a;root [] 输出&#xff1a;[] 示例 3&#xff1a; 输入&#xff1a;roo…