HttpOperater-模拟HTTP操作类
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions; namespace Whir.Software.DocumentDownLoader.Library
{
/// <summary>
/// 模拟HTTP操作
/// </summary>
public class HttpOperater
{
/// <summary>
/// 发起Http请求
/// </summary>
/// <param name="httpRequestType">请求方式</param>
/// <param name="url">请求地址</param>
/// <param name="cookieInput">请求时传入的cookie</param>
/// <param name="cookieOutput">服务器返回的cookie</param>
/// <param name="postData">发送数据</param>
/// <returns></returns>
public static string DoRequest(HttpRequestType httpRequestType, string url, string cookieInput, ref string cookieOutput, string postData)
{
string response;
try
{
const string windowsUserName = "";
const string windowsPwd = "";
const string userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36";
const string accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
const string acceptLanguage = "zh-CN,zh;q=0.8";
const string acceptEncoding = "gzip,deflate,sdch";
CookieContainer cookieContainer = GetCookie(url, cookieInput); var newUri = new Uri(url);
var request = (HttpWebRequest)WebRequest.Create(newUri);
request.PreAuthenticate = true;
if (windowsUserName.Length > 0 & windowsPwd.Length > 0)
{
request.Credentials = new NetworkCredential(windowsUserName.Trim(), windowsPwd.Trim());
}
request.Timeout = 20000;
request.CookieContainer = cookieContainer;
request.UserAgent = userAgent;
request.Accept = accept;
request.Headers["Accept-Language"] = acceptLanguage;
request.Headers["Accept-Charset"] = acceptEncoding;
request.Headers["Accept-Encoding"] = acceptEncoding;
request.Referer = newUri.AbsoluteUri;
request.Method = httpRequestType == HttpRequestType.GET ? "GET" : "POST";
if (request.Method == "POST")
{
request.ContentType = "application/x-www-form-urlencoded";
byte[] bytes = Encoding.UTF8.GetBytes(postData);
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
}
using (var wr = (HttpWebResponse)request.GetResponse())
{
response = new StreamReader(wr.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
}
CookieCollection cookies = cookieContainer.GetCookies(newUri);
cookieOutput = CookieTostr(cookies);
}
catch (NotSupportedException exception)
{
response = exception.Message;
}
catch (InvalidOperationException exception)
{
response = exception.Message;
}
catch (IOException exception)
{
response = exception.Message;
}
catch (Exception exception)
{
response = exception.Message;
}
return response;
}
/// <summary>
/// 设置cookie域
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="cookieInput">cookie</param>
/// <returns></returns>
private static CookieContainer GetCookie(string url, string cookieInput)
{
var cookieContainer = new CookieContainer();
var cookies = new CookieCollection();
string[] cookiesArr = cookieInput.Split(';');
foreach (string s in cookiesArr)
{
string[] keyValuePair = s.Split('=');
if (keyValuePair.Length > 1)
{
var cookie = new Cookie
{
Name = keyValuePair[0].Trim(),
Value = keyValuePair[1].Trim(),
Domain = GetDomain(url).Trim()//设置cookie域
};
cookies.Add(cookie);
}
}
cookieContainer.Add(cookies);
return cookieContainer;
}
/// <summary>
/// 通过Url取得域
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private static string GetDomain(string url)
{
var regex = new Regex("(?i)http[s]*://(?<domain>[\\w|.]*)",
RegexOptions.CultureInvariant | RegexOptions.Compiled);
return regex.Match(url).Groups["domain"].Value;
} /// <summary>
/// 将cookie转为字符串
/// </summary>
/// <param name="cookies"></param>
/// <returns></returns>
private static string CookieTostr(CookieCollection cookies)
{
return cookies.Cast<Cookie>()
.Aggregate(string.Empty, (current, c) => current + (c.Name + "=" + c.Value + ";"));
}
} /// <summary>
/// HTTP请求方式
/// </summary>
public enum HttpRequestType
{
/// <summary>
/// GET
/// </summary>
GET = 1, /// <summary>
/// POST
/// </summary>
POST = 2
}
}
注:使用时,ref string cookiesOutput参数是服务器返回的Cookie,需保存用于下次请求。
HttpOperater-模拟HTTP操作类的更多相关文章
- Util应用程序框架公共操作类(三):数据类型转换公共操作类(扩展篇)
上一篇以TDD方式介绍了数据类型转换公共操作类的开发,并提供了单元测试和实现代码,本文将演示通过扩展方法来增强公共操作类,以便调用时更加简化. 下面以字符串转换为List<Guid>为例进 ...
- C# 字符串操作类
using System; using System.Collections.Generic; using System.Text; using System.Collections; using S ...
- PHP FTP操作类( 上传、拷贝、移动、删除文件/创建目录 )
/** * 作用:FTP操作类( 拷贝.移动.删除文件/创建目录 ) * 时间:2006/5/9 * 作者:欣然随风 * QQ:276624915 */ class class_ftp { publi ...
- (实用篇)PHP ftp上传文件操作类
<?php /** * 作用:FTP操作类( 拷贝.移动.删除文件/创建目录 ) */ class class_ftp { public $off; // 返回操作状态(成功/失败) publi ...
- C# 文件操作类大全
C# 文件操作类大全 时间:2015-01-31 16:04:20 阅读:1724 评论:0 收藏:0 [点我收藏+] 标签: 1.创建文件夹 //usin ...
- firefox下载文件弹出框之终极解决方案-vbs模拟键盘操作
由于近期一直被firefox的保存文件弹出框困扰,摸索尝试过几种方法,已有的方法可以跑通但是对对效果不太满意,因此一直在寻找合适的解决办法. 最近发现了也可以通过VBS来处理弹出框,速度也不错,其原理 ...
- PHP模拟链表操作
PHP模拟链表操作 一.总结 1.类成员用的是-> 2.对象节点相连的话,因为是对象,所以不用取地址符号 3.数组传递参数的时候传引用的方法 ,& 二.PHP模拟链表操作 代码一: /* ...
- php的FTP操作类
class_ftp.php <?php /** * 作用:FTP操作类( 拷贝.移动.删除文件/创建目录 ) */ class class_ftp { public $off; // 返回操作状 ...
- python sqlite3操作类扩展,包含数据库分页
一.原因 最近在使用python3和sqlite3编辑一些小程序,由于要使用数据库,就离不开增.删.改.查,sqlite3的操作同java里的jdbc很像,于是就想找现成的操作类,找来找去,发现一个 ...
随机推荐
- 2009年末最强梅麻呂3D动画游戏大作 汉化补丁
[游戏名称]:Yin荡游戯Ω(前编)-闇の眷族vs女ドラゴン- (名字请自己补) [游戏厂商]:梅麻吕3D [发售日期]:2010年04月16日 游戏评价: 梅麻呂的3D作品能够说是如今3D动画中最好 ...
- android基础知识普及
1.密度问题及相互转换 测试机 philips w732 480X800 density 1.5 scaledDensity 1.6500001 通过 context.getResources().g ...
- leetCode(28):Contains Duplicate II
Given an array of integers and an integer k, find out whether there there are two distinct indices i ...
- VC获得控制台HWND GetConsoleHwnd
HWND GetConsoleHwnd(void) { #define MY_BUFSIZE 1024 // Buffer size for console window titles. HWND h ...
- Python学习(六)模块 —— 第三方库
Python 第三方库 安装第三方库 在Python中,安装第三方库包,是通过setuptools这个工具完成的.Python有两个封装了setuptools的包管理工具:easy_install和p ...
- OpenCV学习(6) 文件和Mat之间的数据交换
有时候为了便于调试算法,我们需要从文本文件或二进制文件中读取数据,并把数据放到相应的矩阵中去.我们通常可以通过下面的函数实现. 1.从二进制文件中读取数据. 新建一个txt文 ...
- java 五子棋之人机对战思路详解
最近做了五子棋,记录下自己完成五子棋的人机对战的思路. 首先,思路是这样的:每当人手动下一颗棋子(黑子)的时候,应当遍历它周围棋子的情况,并赋予周围棋子一定的权值,当在机器要下棋子(白子)守护之前,会 ...
- with(nolock)解释
摘自: http://blog.sina.com.cn/s/blog_5fafba5e010113kr.html with(nolock)解释 所有Select加 With (NoLock)解决阻 ...
- akka模块
模块 Akka的模块化做得非常好,它为不同的功能提供了不同的Jar包. akka-actor-2.0.jar – 标准Actor, 有类型Actor,等等 akka-remote-2.0.jar – ...
- ionic的加载功能
下面是代码(黄色背景的是加载功能的代码): <html ng-app="ionicApp"> <head> <meta charset="u ...