C# 模拟http请求网页数据 [网页爬虫]
using System;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using FTE.Framework.Log4NetService; namespace Proxy.BllServices
{
/// <summary>
/// http访问类
/// </summary>
public class HttpHelper
{
/// <summary>
/// 访问失败的统一返回字符
/// </summary>
public String ErrorReturn { get; private set; } = "HttpHelper access error!"; /// <summary>
/// 登录后保存的cookie
/// </summary>
private CookieContainer Cookie = new CookieContainer(); /// <summary>
/// http post 访问网页
/// </summary>
/// <param name="Url"></param>
/// <param name="postDataStr"></param>
/// <returns></returns>
public string HttpPostString(string Url, string postDataStr)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
request.CookieContainer = Cookie;
Stream myRequestStream = request.GetRequestStream();
StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
myStreamWriter.Write(postDataStr);
myStreamWriter.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Cookies = Cookie.GetCookies(response.ResponseUri); Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close(); return retString;
}
catch (Exception ex)
{
LoggerManagerSingle.Instance.Error("http post 网站出错", ex);
} return ErrorReturn;
} public string HttpGet(string Url, string postDataStr)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
request.CookieContainer = Cookie; HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close(); return retString;
}
catch (Exception ex)
{
LoggerManagerSingle.Instance.Error("http get 网站出错", ex);
} return ErrorReturn;
} /// <summary>
/// 使用form方式post数据[不包含文件]
/// </summary>
/// <param name="url"></param>
/// <param name="stringDict"></param>
/// <returns></returns>
public string HttpPostForm(string url, NameValueCollection stringDict)
{
try
{
string responseContent;
var memStream = new MemoryStream();
var webRequest = (HttpWebRequest)WebRequest.Create(url);
// 边界符
var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
// 边界符
var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
// 最后的结束符
var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n"); // 设置属性
webRequest.CookieContainer = Cookie;
webRequest.Method = "POST";
webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
// 写入字符串的Key
var stringKeyHeader = "\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\"" +
"\r\n\r\n{1}\r\n"; foreach (byte[] formitembytes in from string key in stringDict.Keys
select string.Format(stringKeyHeader, key, stringDict[key])
into formitem
select Encoding.UTF8.GetBytes(formitem))
{
memStream.Write(formitembytes, 0, formitembytes.Length);
} // 写入最后的结束边界符
memStream.Write(endBoundary, 0, endBoundary.Length); webRequest.ContentLength = memStream.Length; var requestStream = webRequest.GetRequestStream(); memStream.Position = 0;
var tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length);
requestStream.Close(); var httpWebResponse = (HttpWebResponse)webRequest.GetResponse(); using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(),
Encoding.GetEncoding("utf-8")))
{
responseContent = httpStreamReader.ReadToEnd();
} httpWebResponse.Close();
webRequest.Abort(); return responseContent;
}
catch (Exception ex)
{
LoggerManagerSingle.Instance.Error("http form post 网站出错", ex);
} return ErrorReturn;
}
}
}
调用例子:
//1.
helper.HttpPostString("http://192.168.1.1/", "luci_username=root&luci_password=password"); //2.
NameValueCollection stringDict = new NameValueCollection();
stringDict.Add("token", token);
stringDict.Add("cbid.wireless.default_radio1.ssid", "everTestWifi");
helper.HttpPostData("http://192.168.1.1/cgi-bin/luci/admin/network/wireless/radio1.network2", stringDict);
参考连接:
http://www.cnblogs.com/xssxss/archive/2012/07/03/2574554.html
http://blog.csdn.net/flymorn/article/details/6769722
C# 模拟http请求网页数据 [网页爬虫]的更多相关文章
- php模拟POST请求提交数据
php模拟POST请求提交数据 1.基于fsockopen function phppost00($jsonString){ $URL='https://www.jy.com/phppostok.ph ...
- php curl模拟post请求提交数据样例总结
在php中要模拟post请求数据提交我们会使用到curl函数,以下我来给大家举几个curl模拟post请求提交数据样例有须要的朋友可參考參考.注意:curl函数在php中默认是不被支持的,假设须要使用 ...
- php curl模拟post请求提交数据例子总结
php curl模拟post请求提交数据例子总结 [导读] 在php中要模拟post请求数据提交我们会使用到curl函数,下面我来给大家举几个curl模拟post请求提交数据例子有需要的朋友可参考参考 ...
- Http协议以及模拟http请求发送数据
1 为什么要使用http协议 假设我现在有两个客户端浏览器,一个是google,一个是IE浏览器:我现在有两个服务器,一个是tomcat,一个是JBoss;在最初的情况下是:如果google要往tom ...
- php curl模拟post请求提交数据
最近在做校园图书馆图书信息的采集程序,既然是图书馆图书的采集,肯定有提交搜索的页面,无非是post提交,让我想到了curl模拟提交,首先通过firebug进行抓包查询下post提交后的格式如下: tx ...
- php curl模拟post请求的例子
curl 在php中要模拟post请求数据提交我们会使用到curl函数,下面我来给大家举几个curl模拟post请求提交数据例子有需要的朋友可参考参考. 注意:curl函数在php中默认是不被支持的, ...
- 使用webdriver+urllib爬取网页数据(模拟登陆,过验证码)
urilib是python的标准库,当我们使用Python爬取网页数据时,往往用的是urllib模块,通过调用urllib模块的urlopen(url)方法返回网页对象,并使用read()方法获得ur ...
- 爬虫---selenium动态网页数据抓取
动态网页数据抓取 什么是AJAX: AJAX(Asynchronouse JavaScript And XML)异步JavaScript和XML.过在后台与服务器进行少量数据交换,Ajax 可以使网页 ...
- 网络爬虫中Fiddler抓取PC端网页数据包与手机端APP数据包
1 引言 在编写网络爬虫时,第一步(也是极为关键一步)就是对网络的请求(request)和回复(response)进行分析,寻找其中的规律,然后才能通过网络爬虫进行模拟.浏览器大多也自带有调试工具可以 ...
随机推荐
- windows server 2016 支持多用户远程登录
服务器设置多用户同时远程桌面,可以提高访问效率,避免人多抢登服务器. 1. 首先需要先安装远程桌面服务 配置组策略,运行框输入gpedit.msc,打开计算机配置–>管理模板—>wind ...
- 58. jdk1.5新特性之静态导入
jdk1.5新特性之--------静态导入 作用:简化书写(在我们使用静态方法的时候要用 类名.方法名的方式调用.而用静态导入只需要写方法名就可以调用) 语法: 1.作用于一个方法: ...
- leetcode-160场周赛-5238-找出给定方程的正整数解
题目描述: class Solution: def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[Li ...
- MySQL - primary key PK unique key,key PK index
primary key PK unique key 总结 primary key = unique + not null 主键不能为空每个字段值都不重复,unique可以为空,非空字段不重复 uniq ...
- Vue源码------------- 数据响应系统的基本思路
在 Vue 中,我们可以使用 $watch 观测一个字段,当字段的值发生变化的时候执行指定的观察者,如下: var vm = new Vue({ data: { num:1 } }) vm.$watc ...
- go语言将函数作为参数传递
Go语言函数作为参数传递,目前给我的感觉几乎和C/C++一致.非常的灵活. import "fmt" import "time" func goFunc1(f ...
- GitHub 万星推荐:黑客成长技术清单
GitHub 万星推荐:黑客成长技术清单 导语:如果你需要一些安全入门引导,“Awesome Hacking”无疑是最佳选择之一. 最近两天,在reddit安全板块和Twitter上有个GitHub项 ...
- 关于“Unknown or unsupported command 'install'”问题解决的小结
经常需要在COMMAND命令中安装第三方库,有时会碰到“Unknown or unsupported command 'install'”这种报错. 刚开始时,以为是环境变量里面没有配置:PYTHON ...
- springboot入门级笔记
springboot亮点:不用配置tomcat springboot不支持jsp 准备:配置jdk 配置maven 访问https://start.spring.io/ 并生成自己的springboo ...
- Django+telnetlib实现webtelnet
说明 基于 python3.7 + django 2.2.3 实现的 django-webtelnet.有兴趣的同学可以在此基础上稍作修改集成到自己的堡垒机中. 项目地址:https://github ...