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. JAVA RMI调用实战学习

    JAVA RMI 实战示例,参考网址: http://diaoge.iteye.com/blog/245170 这个示例很清楚地阐释了rmi的使用方法, 但示例都是放在一起的, 实际使用中我们可能会将 ...

  2. FIS3中使用less

    安装插件: npm install -g fis-parser-less npm install -g fis3-postpackager-loader 配置:fis-conf.js 使用fis-pa ...

  3. debian下安装mysql

    apt-get install mysql-client mysql-server 中间会要你设置password,设置后后就自己主动启动mysql了 能够用ps -ef|grep mysql 这样能 ...

  4. JSP如何导入ckeditor

    <textarea rows="3" cols="100" id="editor1"></textarea> < ...

  5. iFrame的妙用

    (作者: Glen,返利网资深工程师,曾在EA等公司任职) 最近工作有个在项目-布兜收藏夹.简言之就是将喜欢的图片收藏到布兜页面上来,这其中用到了很多关于iframe的方面,总结如下: 1. 作为弹出 ...

  6. 【Networking】(转)一个非常好的epoll+线程池服务器Demo

    (转)一个非常好的epoll+线程池服务器Demo Reply 转载自:http://zhangyafeikimi.javaeye.com/blog/285193 [cpp] /** 张亚霏修改 文件 ...

  7. android学习的网站收集

    1. http://mob.com/#/index 提供分享等统一解决方案 2. http://bbs.apkbus.com/explore/ 这个类似的quroa问答模块,覆盖不错.就是人气,稍差. ...

  8. [Compose] 9. Delay Evaluation with LazyBox

    We rewrite the Box example using lazy evaulation. Here is Box example: const Box = (x) => ({ map: ...

  9. [Webpack] Create Separate webpack Configs for Development and Production with webpack-merge

    The development and production modes in webpack optimize the output in different ways. In developmen ...

  10. PHP与SQL数据库交互中文乱码怎么办

    1 PHP向数据库写入的时候发生乱码 如图所示,把校对放过去看看,是不是别的什么语言 点击修改把字符编码改为utf8_general_ci 2 PHP读取数据库到页面的时候发生乱码 如下图所示 即使在 ...