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的更多相关文章

  1. HttpOperater-模拟HTTP操作类

    using System; using System.IO; using System.Linq; using System.Net; using System.Text; using System. ...

随机推荐

  1. linux文件系统命令(6)---touch和mkdir

    一.目的 本文将介绍linux下新建文件或文件夹.删除文件或文件夹命令.         touch能够新建文件,mkdir用来新建文件夹.rm用来删除文件或文件夹.         本文将选取ubu ...

  2. squid中实现https的透明代理

    国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html内部邀请码:C8E245J (不写邀请码,没有现金送)国内私 ...

  3. Appium+python自动化12-appium元素定位

    前言 appium定位app上的元素,可以通过id,name.class这些属性定位到 一.id定位 1.appium的id属性也就是通过UI Automator工具查看的resource-id属性

  4. Git分支模型

    转自:http://www.cnblogs.com/byeyear/archive/2012/11/28/2793374.html 本文介绍一种使用Git进行源代码管理的分支模型,着重于如何使用Git ...

  5. lua string介绍

    1. string库中所有的字符索引从前往后是1,2,...;从后往前是-1,-2,...2. string库中所有的function都不会直接操作字符串,而是返回一个结果 string.byte(s ...

  6. 🌅 使用 Dawn 快速搭建 React 项目!

    开发一个 React 项目,通常避免不了要去配置 Webpack 和 babel 之类,以支持 commonjs 或 es 模块及各种 es 新语法,及进行 jsx 语法的转义.当然也可以用 crea ...

  7. Mysql5.7.9密码已过有效期的处理过程

    怎么知道系统默认的有效期是多久呢?使用一个普通用登陆[未过期]:默认系统的密码生命周期是360天就是一年这样了: test01@(none) 09:11:43>show variables li ...

  8. 数学图形(2.20)3D曲线

    这一节主要是发布我自己写的3D曲线, (1)立体flower线圈 vertices = a = 10.1 b = 3.1 s = (a + b) / b o = i = to (**PI) j = m ...

  9. windows安装Jupyter Notebook

    这是我自定义的Python 的安装目录 (D:\SoftWare\Python\Python36\Scripts) 1.Jupyter Notebook 和 pip 为了更加方便地写 Python 代 ...

  10. 讨论一下TaskManager中监控磁盘性能的一些小问题

    今天研究了一下命令"diskperf -Y". 我把发现Share给了同事, 原文写在了下面, 就不翻译了. ^_^   Try this command (CMD or Powe ...