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. zookeeper选举机制

    在上一篇文章中我们大致浏览了zookeeper的启动过程,并且提到在Zookeeper的启动过程中leader选举是非常重要而且最复杂的一个环节.那么什么是leader选举呢?zookeeper为什么 ...

  2. redis.conf配置解释

    daemonize:如果需要在后台运行,把该项改为yespidfile:配置多个pid的地址,默认在/var/run/redis.pidbind:绑定ip,设置后只接受来自该ip的请求port:监听端 ...

  3. git和SVN的差别

    1)GIT是分布式的.SVN不是: 这 是GIT和其它非分布式的版本号控制系统,比如SVN.CVS等.最核心的差别.优点是跟其它同事不会有太多的冲突.自己写的代码放在自己电脑上,一段时间后再提交.合并 ...

  4. 深拷贝(deep clone)与浅拷贝(shallow clone)

    深拷贝(deep clone)与浅拷贝(shallow clone) 浅复制(浅克隆):被复制对象的所有变量都含有与原来的对象相同的值,而所有的对其他对象的引用仍然指向原来的对象.换言之,浅复制仅仅复 ...

  5. Elasticsearch 数据搜索篇

    curl 'localhost:9200/_cat/indices?v' health index pri rep docs.count docs.deleted store.size pri.sto ...

  6. log4j.properties 详解与配置步骤总结

    先提供一个项目中使用log4j.properties配置 #log4j.rootLogger=WARN, stdout, file log4j.rootLogger=INFO,console,dail ...

  7. IIS7.5 取消301重定向

    今天想把一个域名解析到对应的www的域名,添加了301重定向.   结果域名解析那里是把www解析到了对应的域名,结果就是重定向循环.立即删除了IIS中重定向,结果还是无法解决.   以为是有缓存,重 ...

  8. STL - 函数作为算法的参数

    函数作为参数,相当于C++的函数指针, C#的委托 for_each函数参数: #include <iostream> #include <algorithm> #includ ...

  9. 小贝_redis高级应用-公布与订阅

    redis高级应用-公布与订阅 一.公布与订阅(pub/sub)功能 二.公布与订阅(pub/sub)机制 三.redis公布与订阅(pub/sub)的实现 一.公布与订阅(pub/sub)功能 Pu ...

  10. codechef The Ball And Cups题解

    The Ball And Cups At the end of a busy day, The Chef and his assistants play a game together. The ga ...