/// <summary>
/// 上传数据参数
/// </summary>
public class UploadEventArgs : EventArgs
{
int bytesSent;
int totalBytes;
/// <summary>
/// 已发送的字节数
/// </summary>
public int BytesSent
{
get { return bytesSent; }
set { bytesSent = value; }
}
/// <summary>
/// 总字节数
/// </summary>
public int TotalBytes
{
get { return totalBytes; }
set { totalBytes = value; }
}
}
/// <summary>
/// 下载数据参数
/// </summary>
public class DownloadEventArgs : EventArgs
{
int bytesReceived;
int totalBytes;
byte[] receivedData;
/// <summary>
/// 已接收的字节数
/// </summary>
public int BytesReceived
{
get { return bytesReceived; }
set { bytesReceived = value; }
}
/// <summary>
/// 总字节数
/// </summary>
public int TotalBytes
{
get { return totalBytes; }
set { totalBytes = value; }
}
/// <summary>
/// 当前缓冲区接收的数据
/// </summary>
public byte[] ReceivedData
{
get { return receivedData; }
set { receivedData = value; }
}
} public class WebClient
{
Encoding encoding = Encoding.Default;
string respHtml = "";
WebProxy proxy;
static CookieContainer cc;
WebHeaderCollection requestHeaders;
WebHeaderCollection responseHeaders;
int bufferSize = ;
public event EventHandler<UploadEventArgs> UploadProgressChanged;
public event EventHandler<DownloadEventArgs> DownloadProgressChanged;
static WebClient()
{
LoadCookiesFromDisk();
}
/// <summary>
/// 创建WebClient的实例
/// </summary>
public WebClient()
{
requestHeaders = new WebHeaderCollection();
responseHeaders = new WebHeaderCollection();
}
/// <summary>
/// 设置发送和接收的数据缓冲大小
/// </summary>
public int BufferSize
{
get { return bufferSize; }
set { bufferSize = value; }
}
/// <summary>
/// 获取响应头集合
/// </summary>
public WebHeaderCollection ResponseHeaders
{
get { return responseHeaders; }
}
/// <summary>
/// 获取请求头集合
/// </summary>
public WebHeaderCollection RequestHeaders
{
get { return requestHeaders; }
}
/// <summary>
/// 获取或设置代理
/// </summary>
public WebProxy Proxy
{
get { return proxy; }
set { proxy = value; }
}
/// <summary>
/// 获取或设置请求与响应的文本编码方式
/// </summary>
public Encoding Encoding
{
get { return encoding; }
set { encoding = value; }
}
/// <summary>
/// 获取或设置响应的html代码
/// </summary>
public string RespHtml
{
get { return respHtml; }
set { respHtml = value; }
}
/// <summary>
/// 获取或设置与请求关联的Cookie容器
/// </summary>
public CookieContainer CookieContainer
{
get { return cc; }
set { cc = value; }
}
/// <summary>
/// 获取网页源代码
/// </summary>
/// <param name="url">网址</param>
/// <returns></returns>
public string GetHtml(string url)
{
HttpWebRequest request = CreateRequest(url, "GET");
respHtml = encoding.GetString(GetData(request));
return respHtml;
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="url">文件URL地址</param>
/// <param name="filename">文件保存完整路径</param>
public void DownloadFile(string url, string filename)
{
FileStream fs = null;
try
{
HttpWebRequest request = CreateRequest(url, "GET");
byte[] data = GetData(request);
fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
fs.Write(data, , data.Length);
}
finally
{
if (fs != null) fs.Close();
}
}
/// <summary>
/// 从指定URL下载数据
/// </summary>
/// <param name="url">网址</param>
/// <returns></returns>
public byte[] GetData(string url)
{
HttpWebRequest request = CreateRequest(url, "GET");
return GetData(request);
}
/// <summary>
/// 向指定URL发送文本数据
/// </summary>
/// <param name="url">网址</param>
/// <param name="postData">urlencode编码的文本数据</param>
/// <returns></returns>
public string Post(string url, string postData)
{
byte[] data = encoding.GetBytes(postData);
return Post(url, data);
}
/// <summary>
/// 向指定URL发送字节数据
/// </summary>
/// <param name="url">网址</param>
/// <param name="postData">发送的字节数组</param>
/// <returns></returns>
public string Post(string url, byte[] postData)
{
HttpWebRequest request = CreateRequest(url, "POST");
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
request.KeepAlive = true;
PostData(request, postData);
respHtml = encoding.GetString(GetData(request));
return respHtml;
}
/// <summary>
/// 向指定网址发送mulitpart编码的数据
/// </summary>
/// <param name="url">网址</param>
/// <param name="mulitpartForm">mulitpart form data</param>
/// <returns></returns>
public string Post(string url, MultipartForm mulitpartForm)
{
HttpWebRequest request = CreateRequest(url, "POST");
request.ContentType = mulitpartForm.ContentType;
request.ContentLength = mulitpartForm.FormData.Length;
request.KeepAlive = true;
PostData(request, mulitpartForm.FormData);
respHtml = encoding.GetString(GetData(request));
return respHtml;
} /// <summary>
/// 读取请求返回的数据
/// </summary>
/// <param name="request">请求对象</param>
/// <returns></returns>
private byte[] GetData(HttpWebRequest request)
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
responseHeaders = response.Headers;
//SaveCookiesToDisk(); DownloadEventArgs args = new DownloadEventArgs();
if (responseHeaders[HttpResponseHeader.ContentLength] != null)
args.TotalBytes = Convert.ToInt32(responseHeaders[HttpResponseHeader.ContentLength]); MemoryStream ms = new MemoryStream();
int count = ;
byte[] buf = new byte[bufferSize];
while ((count = stream.Read(buf, , buf.Length)) > )
{
ms.Write(buf, , count);
if (this.DownloadProgressChanged != null)
{
args.BytesReceived += count;
args.ReceivedData = new byte[count];
Array.Copy(buf, args.ReceivedData, count);
this.DownloadProgressChanged(this, args);
}
}
stream.Close();
//解压
if (ResponseHeaders[HttpResponseHeader.ContentEncoding] != null)
{
MemoryStream msTemp = new MemoryStream();
count = ;
buf = new byte[];
switch (ResponseHeaders[HttpResponseHeader.ContentEncoding].ToLower())
{
case "gzip":
GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress);
while ((count = gzip.Read(buf, , buf.Length)) > )
{
msTemp.Write(buf, , count);
}
return msTemp.ToArray();
case "deflate":
DeflateStream deflate = new DeflateStream(ms, CompressionMode.Decompress);
while ((count = deflate.Read(buf, , buf.Length)) > )
{
msTemp.Write(buf, , count);
}
return msTemp.ToArray();
default:
break;
}
}
return ms.ToArray();
}
/// <summary>
/// 发送请求数据
/// </summary>
/// <param name="request">请求对象</param>
/// <param name="postData">请求发送的字节数组</param>
private void PostData(HttpWebRequest request, byte[] postData)
{
int offset = ;
int sendBufferSize = bufferSize;
int remainBytes = ;
Stream stream = request.GetRequestStream();
UploadEventArgs args = new UploadEventArgs();
args.TotalBytes = postData.Length;
while ((remainBytes = postData.Length - offset) > )
{
if (sendBufferSize > remainBytes) sendBufferSize = remainBytes;
stream.Write(postData, offset, sendBufferSize);
offset += sendBufferSize;
if (this.UploadProgressChanged != null)
{
args.BytesSent = offset;
this.UploadProgressChanged(this, args);
}
}
stream.Close();
}
/// <summary>
/// 创建HTTP请求
/// </summary>
/// <param name="url">URL地址</param>
/// <returns></returns>
private HttpWebRequest CreateRequest(string url, string method)
{
Uri uri = new Uri(url); if (uri.Scheme == "https")
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(this.CheckValidationResult); // Set a default policy level for the "http:" and "https" schemes.
HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Revalidate);
HttpWebRequest.DefaultCachePolicy = policy; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AllowAutoRedirect = false;
request.AllowWriteStreamBuffering = false;
request.Method = method;
if (proxy != null)
request.Proxy = proxy;
request.CookieContainer = cc;
foreach (string key in requestHeaders.Keys)
{
request.Headers.Add(key, requestHeaders[key]);
}
requestHeaders.Clear();
return request;
}
private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
/// <summary>
/// 将Cookie保存到磁盘
/// </summary>
private static void SaveCookiesToDisk()
{
string cookieFile = System.Environment.GetFolderPath(Environment.SpecialFolder.Cookies) + "\\webclient.cookie";
FileStream fs = null;
try
{
fs = new FileStream(cookieFile, FileMode.Create);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formater = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formater.Serialize(fs, cc);
}
finally
{
if (fs != null) fs.Close();
}
}
/// <summary>
/// 从磁盘加载Cookie
/// </summary>
private static void LoadCookiesFromDisk()
{
cc = new CookieContainer();
string cookieFile = System.Environment.GetFolderPath(Environment.SpecialFolder.Cookies) + "\\webclient.cookie";
if (!File.Exists(cookieFile))
return;
FileStream fs = null;
try
{
fs = new FileStream(cookieFile, FileMode.Open, FileAccess.Read, FileShare.Read);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formater = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
cc = (CookieContainer)formater.Deserialize(fs);
}
finally
{
if (fs != null) fs.Close();
}
}
} /// <summary>
/// 对文件和文本数据进行Multipart形式的编码
/// </summary>
public class MultipartForm
{
private Encoding encoding;
private MemoryStream ms;
private string boundary;
private byte[] formData;
/// <summary>
/// 获取编码后的字节数组
/// </summary>
public byte[] FormData
{
get
{
if (formData == null)
{
byte[] buffer = encoding.GetBytes("--" + this.boundary + "--\r\n");
ms.Write(buffer, , buffer.Length);
formData = ms.ToArray();
}
return formData;
}
}
/// <summary>
/// 获取此编码内容的类型
/// </summary>
public string ContentType
{
get { return string.Format("multipart/form-data; boundary={0}", this.boundary); }
}
/// <summary>
/// 获取或设置对字符串采用的编码类型
/// </summary>
public Encoding StringEncoding
{
set { encoding = value; }
get { return encoding; }
}
/// <summary>
/// 实例化
/// </summary>
public MultipartForm()
{
boundary = string.Format("--{0}--", Guid.NewGuid());
ms = new MemoryStream();
encoding = Encoding.Default;
}
/// <summary>
/// 添加一个文件
/// </summary>
/// <param name="name">文件域名称</param>
/// <param name="filename">文件的完整路径</param>
public void AddFlie(string name, string filename)
{
if (!File.Exists(filename))
throw new FileNotFoundException("尝试添加不存在的文件。", filename);
FileStream fs = null;
byte[] fileData = { };
try
{
fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
fileData = new byte[fs.Length];
fs.Read(fileData, , fileData.Length);
this.AddFlie(name, Path.GetFileName(filename), fileData, fileData.Length);
}
catch (Exception)
{
throw;
}
finally
{
if (fs != null) fs.Close();
}
}
/// <summary>
/// 添加一个文件
/// </summary>
/// <param name="name">文件域名称</param>
/// <param name="filename">文件名</param>
/// <param name="fileData">文件二进制数据</param>
/// <param name="dataLength">二进制数据大小</param>
public void AddFlie(string name, string filename, byte[] fileData, int dataLength)
{
if (dataLength <= || dataLength > fileData.Length)
{
dataLength = fileData.Length;
}
StringBuilder sb = new StringBuilder();
sb.AppendFormat("--{0}\r\n", this.boundary);
sb.AppendFormat("Content-Disposition: form-data; name=\"{0}\";filename=\"{1}\"\r\n", name, filename);
sb.AppendFormat("Content-Type: {0}\r\n", this.GetContentType(filename));
sb.Append("\r\n");
byte[] buf = encoding.GetBytes(sb.ToString());
ms.Write(buf, , buf.Length);
ms.Write(fileData, , dataLength);
byte[] crlf = encoding.GetBytes("\r\n");
ms.Write(crlf, , crlf.Length);
}
/// <summary>
/// 添加字符串
/// </summary>
/// <param name="name">文本域名称</param>
/// <param name="value">文本值</param>
public void AddString(string name, string value)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("--{0}\r\n", this.boundary);
sb.AppendFormat("Content-Disposition: form-data; name=\"{0}\"\r\n", name);
sb.Append("\r\n");
sb.AppendFormat("{0}\r\n", value);
byte[] buf = encoding.GetBytes(sb.ToString());
ms.Write(buf, , buf.Length);
}
/// <summary>
/// 从注册表获取文件类型
/// </summary>
/// <param name="filename">包含扩展名的文件名</param>
/// <returns>如:application/stream</returns>
private string GetContentType(string filename)
{
Microsoft.Win32.RegistryKey fileExtKey = null; ;
string contentType = "application/stream";
try
{
fileExtKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(Path.GetExtension(filename));
contentType = fileExtKey.GetValue("Content Type", contentType).ToString();
}
finally
{
if (fileExtKey != null) fileExtKey.Close();
}
return contentType;
}
}

Http 数据操作的更多相关文章

  1. StackExchange.Redis帮助类解决方案RedisRepository封装(字符串类型数据操作)

    本文版权归博客园和作者本人共同所有,转载和爬虫请注明原文链接 http://www.cnblogs.com/tdws/tag/NoSql/ 目录 一.基础配置封装 二.String字符串类型数据操作封 ...

  2. hive数据操作

    mdl是数据操作类的语言,包括向数据表加载文件,写查询结果等操作 hive有四种导入数据的方式 >从本地加载数据 LOAD DATA LOCAL INPATH './examples/files ...

  3. Dapper 数据操作框架

    数据操作DapperFrom NuGet:Install-Package DapperorInstall-Package Dapper.StrongName微型ORM:PetaPoco获得PetaPo ...

  4. Django数据操作F和Q、model多对多操作、Django中间件、信号、读数据库里的数据实现分页

    models.tb.objects.all().using('default'),根据using来指定在哪个库里查询,default是settings中配置的数据库的连接名称. 外话:django中引 ...

  5. coreData数据操作

    // 1. 建立模型文件// 2. 建立CoreDataStack// 3. 设置AppDelegate 接着 // // CoreDataStack.swift // CoreDataStackDe ...

  6. Entity Framework 5.0系列之数据操作

    Entity Framework将概念模型中定义的实体和关系映射到数据源,利用实体框架可以将数据源返回的数据具体化为对象:跟踪对象所做的更改:并发处理:将对象更改传播到数据源等.今天我们就一起讨论如何 ...

  7. 数据操作语言DML与运算符

    数据操作语言DML(添加,修改,删除) 1.添加数据 insert into insert into 表名 (字段列表) values (值列表),值列表要和字段列表按顺序匹配. insert int ...

  8. SQL不同服务器数据库之间的数据操作整理(完整版)

    ---------------------------------------------------------------------------------- -- Author : htl25 ...

  9. C#利用SqlDataAdapte对DataTable进行批量数据操作

    C#利用SqlDataAdapte对DataTable进行批量数据操作,可以让我们大大简化操作数据的代码量,我们几乎不需要循环和不关心用户到底是新增还是修改,更不用编写新增和修改以及删除的SQL语句, ...

  10. 使用Hive或Impala执行SQL语句,对存储在HBase中的数据操作

    CSSDesk body { background-color: #2574b0; } /*! zybuluo */ article,aside,details,figcaption,figure,f ...

随机推荐

  1. vue 动态添加对象属性

    昨天使用vue发现直接给对象添加属性,并不能触发响应更新,后来看文档发现要通过this.$set 函数动态添加才可用,eg: this.$set( obj, key, data)

  2. T100——按xls格式批量导入数据

    弹出File Browser窗口 PRIVATE FUNCTION cxrt020_open_file() DEFINE l_dir LIKE type_t.chr500 DEFINE r_succe ...

  3. 高性能MySQL3_笔记1_Mysql的架构与历史

    第一层:连接处理.授权认证.安全 第二层:mysql的核心功能,包括查询解析.分析.优化.缓存以及所有的内置函数(例如日期.加密.数学函数), 所有跨存储引擎的功能都在这一层实现:存储过程.触发器.视 ...

  4. mysql 8.x 登陆提示 Access denied for user 'root'@'localhost' (using password: YES)

    第一步:修改 /etc/mysql/my.cnf. 在[mysql]下添加skip-grant-table:重启. 第二步:通过mysql命令登陆: flush privileges; use mys ...

  5. CAS实现逻辑(JWT)

    由于没有获取正规做CAS的流程,这里根据网上的资料,写了一个自己觉得还可以的方案流程,留着备用 名称介绍: token:用于验证请求是否合法 refreshToken:当token失效后,客户端发送t ...

  6. C#面向对象20 序列化和反序列化

    序列化和反序列化 序列化是把一个内存中的对象的信息转化成一个可以持久化保存的形式,以便于保存或传输,序列化的主要作用是不同平台之间进行通信,常用的有序列化有json.xml.文件等   一.序列化为j ...

  7. 异常-JDK7针对多个异常的处理方案

    package cn.itcast_02; /* * JDK7出现了一个新的异常处理方案: * try{ * * }catch(异常名1 | 异常名2 | ... 变量 ) { * ... * } * ...

  8. TensorFlow良心入门教程

    All the matrials come from Machine Learning class in Polyu,HK and I reorganize them and add referenc ...

  9. Python算法题(二)——国际象棋棋盘(排列组合问题,最小的K个数)

    题目一(输出国际象棋棋盘)  分析: 用i控制行,j来控制列,根据i+j的和的变化来控制输出黑方格,还是白方格.   主要代码: for i in range(8): for j in range(8 ...

  10. 1 设置 dev express控件RepositoryItemLookUpEdit数据源的方法

    private void SetLookUpEditData(Type enumType, DevExpress.XtraEditors.Repository.RepositoryItemLookUp ...