Http 辅助类
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Cache;
using System.Text; namespace ePlatform.Processor
{
/// <summary>
/// Http处理
/// </summary>
public static class Http
{
/// <summary>
/// 创建访问URL的Response
/// </summary>
/// <param name="uri"></param>
/// <param name="mycookies"></param>
/// <returns></returns>
public static HttpWebResponse GetWebResponse(string uri, ref CookieCollection mycookies)
{
try
{
//请求
var req = HttpWebRequest.Create(uri) as HttpWebRequest;
var cookies = new CookieContainer(); req.KeepAlive = true;
req.AllowAutoRedirect = true;
req.AllowWriteStreamBuffering = true;
req.Credentials = CredentialCache.DefaultCredentials;
req.Referer = "http://www.lanxe.net/";
req.Timeout = 20000;
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)";
req.CookieContainer = cookies; //加入额外的Cookie
if (mycookies != null)
{
foreach (Cookie item in mycookies)
{
cookies.Add(item);
}
} //回应
var res = req.GetResponse() as HttpWebResponse;
mycookies = cookies.GetCookies(req.RequestUri);
res.Cookies = mycookies; return res;
}
catch
{
return null;
}
} /// <summary>
/// 向网站Post数据
/// </summary>
/// <param name="uri"></param>
/// <param name="mycookies"></param>
/// <param name="encoding"></param>
/// <param name="data"></param>
/// <returns></returns>
public static string PostData(string uri, ref CookieCollection mycookies, string encoding, string data)
{
var encode = getEncoding(encoding);
var datas = encode.GetBytes(data);
var length = datas.Length; try
{
//请求
var req = HttpWebRequest.Create(uri) as HttpWebRequest;
var cookies = new CookieContainer();
var cache = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); req.KeepAlive = true;
req.AllowAutoRedirect = true;
req.AllowWriteStreamBuffering = true;
req.Credentials = CredentialCache.DefaultCredentials;
req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
req.Accept = "*/*";
req.Referer = "http://translate.google.com.hk/";
req.Timeout = 20000;
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)";
req.CachePolicy = cache;
req.Method = "POST";
req.ContentLength = length;
req.CookieContainer = cookies; //加入额外的Cookie
if (mycookies != null)
{
foreach (Cookie item in mycookies)
{
cookies.Add(item);
}
} //发送内容
var stream = req.GetRequestStream();
stream.Write(datas, 0, length);
stream.Close(); //获取返回的数据
var res = (HttpWebResponse)req.GetResponse();
mycookies = cookies.GetCookies(req.RequestUri);
return getHtml(res, encode);
}
catch
{
return null;
}
} /// <summary>
/// 获取网页源代码
/// </summary>
/// <param name="uri"></param>
/// <param name="encodeName"></param>
/// <param name="outCookies"></param>
/// <returns></returns>
public static string GetHtml(string uri, string encodeName, ref CookieCollection mycookies)
{
var response = GetWebResponse(uri, ref mycookies);
if (response == null)
{
return null;
}
try
{
var encode = getEncoding(encodeName);
return getHtml(response, encode);
}
catch
{
return null;
}
} /// <summary>
/// 获取网页流图像
/// </summary>
/// <param name="uri"></param>
/// <param name="mycookies"></param>
/// <param name="length"></param>
/// <returns></returns>
public static Image GetImage(string uri, ref CookieCollection mycookies, out long length)
{
length = 0;
var res = GetWebResponse(uri, ref mycookies);
if (res == null)
{
return null;
}
try
{
length = res.ContentLength;
Stream stream = res.GetResponseStream();
return Image.FromStream(stream, true);
}
catch (Exception ex)
{
throw ex;
}
} /// <summary>
/// 根据名称获取网页编码格式
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
static Encoding getEncoding(string name)
{
if (string.IsNullOrEmpty(name))
{
return Encoding.UTF8;
}
else if (name.ToLower() == "default")
{
return Encoding.Default;
}
else
{
return Encoding.GetEncoding(name);
}
} /// <summary>
/// 从Response中获取HTML内容
/// </summary>
/// <param name="res"></param>
/// <param name="encode"></param>
/// <returns></returns>
static string getHtml(HttpWebResponse res, Encoding encode)
{
var outs = new StringBuilder();
var stream = res.GetResponseStream();
var reader = new StreamReader(stream, encode); // 每次读取1024
var buffer = new char[1024];
var count = reader.Read(buffer, 0, 1024);
while (count > 0)
{
outs.Append(new String(buffer, 0, count));
count = reader.Read(buffer, 0, 1024);
} // 读取完毕
reader.Close();
stream.Close(); return outs.ToString();
}
}
}
Http 辅助类的更多相关文章
- Java的几个同步辅助类
Java为我们提供了一些同步辅助类,利用这些辅助类我们可以在多线程编程中,灵活地把握线程的状态. CountDownLatch CountDownLatch一个同步辅助类,在完成一组正在其他线程中执行 ...
- ASP.NET Core 中文文档 第四章 MVC(3.6.2 )自定义标签辅助类(Tag Helpers)
原文:Authoring Tag Helpers 作者:Rick Anderson 翻译:张海龙(jiechen) 校对:许登洋(Seay) 示例代码查看与下载 从 Tag Helper 讲起 本篇教 ...
- DateHelper.cs日期时间操作辅助类C#
//==================================================================== //** Copyright © classbao.com ...
- 同步辅助类CountDownLatch用法
CountDownLatch是一个同步辅助类,犹如倒计时计数器,创建对象时通过构造方法设置初始值,调用CountDownLatch对象的await()方法则使当前线程处于等待状态,调用countDow ...
- 基于MemoryCache的缓存辅助类
背景: 1. 什么是MemoryCache? memoryCache就是用电脑内存做缓存处理 2.使用范围? 可用于不常变的数据,进行保存在内存中,提高处理效率 代码: /// <summary ...
- java中被各种XXUtil/XXUtils辅助类恶心到了,推荐这种命名方法
且看一下有多少个StringUtils 列举一下XXUtil/XXUtils恶劣之处 1. 不知道该用XXUtil还是用XXUtils, 或者XXHelper, XXTool 2. 不知道该用a.ja ...
- NPOI操作Excel辅助类
/// <summary> /// NPOI操作excel辅助类 /// </summary> public static class NPOIHelper { #region ...
- ByteBuf和相关辅助类
当我们进行数据传输的时候,往往需要使用到缓冲区,常用的缓冲区就是JDK NIO类库提供的java.nio.Buffer. 实际上,7种基础类型(Boolean除外)都有自己的缓冲区实现,对于NIO编程 ...
- Bootstrap<基础九>辅助类
Bootstrap 中的一些可能会派上用场的辅助类. 文本 以下不同的类展示了不同的文本颜色.如果文本是个链接鼠标移动到文本上会变暗: 类 描述 .text-muted "text-mu ...
- 压缩文本、字节或者文件的压缩辅助类-GZipHelper
下面为大家介绍一.NET下辅助公共类GZipHelper,该工具类主要作用是对文本.字符.文件等进行压缩与解压.该类主要使用命名空间:System.IO.Compression下的GZipStream ...
随机推荐
- Js点餐加减数量
<button class="add-on" onclick="chgNum(1,'del')" ><i class="icon-m ...
- qt 运行提示:error: cannot find -lGL
安装:libgl1-mesa-dev问题解决 y@y:~$ sudo apt-get install libgl1-mesa-dev
- Microsoft Detours 2.1简介
http://blog.163.com/qcb_163/blog/static/9545466420117851038971/ Microsoft Detours 2.1简介 2011-08-0817 ...
- android:ListView的局部刷新
1.简介 对于android中的ListView刷新机制,大多数的程序员都是很熟悉的,修改或者添加adapter中的数据源之后,然后调用notifyDataSetChanged()刷新ListView ...
- 【HDOJ】1078 FatMouse and Cheese
这道题目是典型的DFS+记忆化搜索, DP思想.符合:含重叠子问题,无后效性等特点. #include <cstdio> #include <cstring> #include ...
- 【转】vim 修改tab为四个空格
原文网址:http://blog.sina.com.cn/s/blog_620ccfbf01010erz.html 为了vim更好的支持python写代码,修改tab默认4个空格有两种设置方法: 1. ...
- bzoj3573[Hnoi2014]米特运输
http://www.lydsy.com/JudgeOnline/problem.php?id=3573 好吧,虽然这是day1最后一题,但却是最水的一题....(前提:看懂题目) 仔细看题! 仔细看 ...
- Win8 系统下串口出现叹号 异常(10)
在网上找了些资料,自己试了一下可行,具体步骤就是把win8系统自动更新驱动的功能给关掉,然后自己下载可用的驱动.具体可以看 http://download.csdn.net/detail/wuu_ex ...
- [Data Structure] 二叉搜索树(Binary Search Tree) - 笔记
1. 二叉搜索树,可以用作字典,或者优先队列. 2. 根节点 root 是树结构里面唯一一个其父节点为空的节点. 3. 二叉树搜索树的属性: 假设 x 是二叉搜索树的一个节点.如果 y 是 x 左子树 ...
- X Window、GNOME和KDE之间的关系
原文地址:http://blog.csdn.net/jincf2011/article/details/6362923 X Window, 即X Windows图形用户接口,它并不是一个软件,而是一个 ...