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请求网页数据 [网页爬虫]的更多相关文章

  1. php模拟POST请求提交数据

    php模拟POST请求提交数据 1.基于fsockopen function phppost00($jsonString){ $URL='https://www.jy.com/phppostok.ph ...

  2. php curl模拟post请求提交数据样例总结

    在php中要模拟post请求数据提交我们会使用到curl函数,以下我来给大家举几个curl模拟post请求提交数据样例有须要的朋友可參考參考.注意:curl函数在php中默认是不被支持的,假设须要使用 ...

  3. php curl模拟post请求提交数据例子总结

    php curl模拟post请求提交数据例子总结 [导读] 在php中要模拟post请求数据提交我们会使用到curl函数,下面我来给大家举几个curl模拟post请求提交数据例子有需要的朋友可参考参考 ...

  4. Http协议以及模拟http请求发送数据

    1 为什么要使用http协议 假设我现在有两个客户端浏览器,一个是google,一个是IE浏览器:我现在有两个服务器,一个是tomcat,一个是JBoss;在最初的情况下是:如果google要往tom ...

  5. php curl模拟post请求提交数据

    最近在做校园图书馆图书信息的采集程序,既然是图书馆图书的采集,肯定有提交搜索的页面,无非是post提交,让我想到了curl模拟提交,首先通过firebug进行抓包查询下post提交后的格式如下: tx ...

  6. php curl模拟post请求的例子

    curl 在php中要模拟post请求数据提交我们会使用到curl函数,下面我来给大家举几个curl模拟post请求提交数据例子有需要的朋友可参考参考. 注意:curl函数在php中默认是不被支持的, ...

  7. 使用webdriver+urllib爬取网页数据(模拟登陆,过验证码)

    urilib是python的标准库,当我们使用Python爬取网页数据时,往往用的是urllib模块,通过调用urllib模块的urlopen(url)方法返回网页对象,并使用read()方法获得ur ...

  8. 爬虫---selenium动态网页数据抓取

    动态网页数据抓取 什么是AJAX: AJAX(Asynchronouse JavaScript And XML)异步JavaScript和XML.过在后台与服务器进行少量数据交换,Ajax 可以使网页 ...

  9. 网络爬虫中Fiddler抓取PC端网页数据包与手机端APP数据包

    1 引言 在编写网络爬虫时,第一步(也是极为关键一步)就是对网络的请求(request)和回复(response)进行分析,寻找其中的规律,然后才能通过网络爬虫进行模拟.浏览器大多也自带有调试工具可以 ...

随机推荐

  1. RLO文件名欺骗

    windows下面,支持一种特殊的unicode字符RLO,一个字符串中如果有这个字符的话,那么在windows下显示时,就会把RLO右侧的字符串逆序显示出来,原始字符串:abcd[RLO]efgh, ...

  2. 当一个页面中有多个form表单并且有重名的元素时,js获取指定form表单中的指定元素

    有时候我们会在一个页面中写了多个form表单,碰巧多个form表单中又有相同名称的元素,而我们又不想改名字,这个时候就能用到 $("#form1 #div1").val() 好玩吧 ...

  3. 使用appium1.4在android8.0真机上测试程序时报错command failed shell "ps 'uiautomator'"的解决方式

    appium1.4,运行自动化脚本时提示 org.openqa.selenium.SessionNotCreatedException: A new session could not be crea ...

  4. Python改变当前工作目录

    import os print(os.getcwd()) # 打印当前工作目录 os.chdir('/Users/<username>/Desktop/') # 将当前工作目录改变为`/U ...

  5. Vue学习笔记【2】——Vue指令之 - v-cloak、v-text和v-html

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  6. AutoCAD2016简体中文破解版32位64位下载

    AutoCAD2016序列号:666-69696969 667-98989898 400-45454545 066-66666666(任意一个) AutoCAD2016产品密钥:001H1 AutoC ...

  7. 炼数成金数据分析课程---10、python中如何画图

    炼数成金数据分析课程---10.python中如何画图 一.总结 一句话总结: 主要matplotlib库,pandas中也可以画一些基础图 大纲+实例快速学习法 1.matplotlib的最简单画图 ...

  8. 正则表达式替换字符串中的html标签

    正则表达式替换字符串中的html标签 ··· var newStr = str.replace(/<[^>]+>/g, ''); ···

  9. 记录解决java.io.IOException: Server returned HTTP response code: 500 for URL:xxxxxxxx

    踩坑经历 因为项目需要去对接别的接口,使用URLConnection POST请求https接口,发送json数组时遇到java.io.IOException: Server returned HTT ...

  10. Access数据库中自动编号字段重置为1

    在清空一张ACESS数据库表后,在重添加数据之前,希望此表的自动编号能从1开始,怎么办呢? 下面的方法告诉我们,除了通过转存数据库表的方法外,还有几种更简单的方法: 方法一(前提:数据库表可带内容进行 ...