C# Http访问帮助类,支持get post请求文件下载 [
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text; namespace XX.Common.Http
{
/// <summary>
/// Http访问帮助类
/// </summary>
public class HttpHelper
{
/// <summary>
/// HttpWebRequest 通过Post
/// </summary>
/// <param name="url">URI</param>
/// <param name="postData">post数据</param>
/// <returns></returns>
public static string PostDataGetHtml(string url, string postData)
{
try
{
byte[] data = Encoding.UTF8.GetBytes(postData); Uri uri = new Uri(url);
HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
if (req == null)
{
return "Network error:" + new ArgumentNullException("httpWebRequest").Message;
}
req.Method = "POST";
req.KeepAlive = true;
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
req.AllowAutoRedirect = true; Stream outStream = req.GetRequestStream();
outStream.Write(data, , data.Length);
outStream.Close(); var res = req.GetResponse() as HttpWebResponse;
if (res == null)
{
return "Network error:" + new ArgumentNullException("HttpWebResponse").Message;
}
Stream inStream = res.GetResponseStream();
var sr = new StreamReader(inStream, Encoding.UTF8);
string htmlResult = sr.ReadToEnd(); return htmlResult;
}
catch (Exception ex)
{
return "网络错误(Network error):" + ex.Message;
}
} /// <summary>
/// HttpWebRequest 通过get
/// </summary>
/// <param name="url">URI</param>
/// <returns></returns>
public static string GetDataGetHtml(string url)
{
try
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "GET";
//对发送的数据不使用缓存
httpWebRequest.AllowWriteStreamBuffering = false;
httpWebRequest.Timeout = ;
httpWebRequest.ServicePoint.Expect100Continue = false; HttpWebResponse webRespon = (HttpWebResponse)httpWebRequest.GetResponse();
Stream webStream = webRespon.GetResponseStream();
if (webStream == null)
{
return "网络错误(Network error):" + new ArgumentNullException("webStream");
}
StreamReader streamReader = new StreamReader(webStream, Encoding.UTF8);
string responseContent = streamReader.ReadToEnd(); webRespon.Close();
streamReader.Close(); return responseContent;
}
catch (Exception ex)
{
return "网络错误(Network error):" + ex.Message;
}
} /// <summary>
/// HttpWebRequest 通过get
/// </summary>
/// <param name="url">URI</param>
/// <returns></returns>
public static bool GetDataGetHtml(string url, string filePath,ref string mg)
{
try
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "GET";
//对发送的数据不使用缓存
httpWebRequest.AllowWriteStreamBuffering = false;
httpWebRequest.Timeout = ;
httpWebRequest.ServicePoint.Expect100Continue = false; HttpWebResponse webRespon = (HttpWebResponse)httpWebRequest.GetResponse();
Stream webStream = webRespon.GetResponseStream();
if (webStream == null)
{
return false;
}
StreamReader streamReader = new StreamReader(webStream, Encoding.UTF8);
string responseContent = streamReader.ReadToEnd();
mg = responseContent;
webRespon.Close();
streamReader.Close();
if (responseContent.ToUpper().IndexOf("NULL") > -)
{
return false;
}
else
{
FileStream fs = new FileStream(filePath, FileMode.Create);
var buff = Encoding.UTF8.GetBytes(responseContent);
fs.Write(buff, buff.Length, );
fs.Close();
return true;
}
}
catch (Exception ex)
{
return false;
}
} /// <summary>
/// 将本地文件上传到指定的服务器(HttpWebRequest方法)
/// </summary>
/// <param name="address">文件上传到的服务器</param>
/// <param name="fileNamePath">要上传的本地文件(全路径)</param>
/// <param name="saveName">文件上传后的名称</param>
/// <returns>成功返回1,失败返回0</returns>
public static int Upload_Request(string address, string fileNamePath, string saveName)
{
// 要上传的文件
try
{
if (!File.Exists(fileNamePath))
{
return ;
}
FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
return Upload_Request(address, fs, saveName);
}
catch (Exception ex)
{
return ;
}
} /// <summary>
/// 将本地文件流上传到指定的服务器(HttpWebRequest方法)
/// </summary>
/// <param name="address">文件上传到的服务器</param>
/// <param name="fileStream">要上传的本地文件流</param>
/// <param name="saveName">文件上传后的名称</param>
/// <returns>成功返回1,失败返回0</returns>
public static int Upload_Request(string address, Stream fileStream, string saveName)
{
int returnValue = ;
fileStream.Position = ;
var r = new BinaryReader(fileStream);
//时间戳
string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n");
//请求头部信息
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(strBoundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append("file");
sb.Append("\"; filename=\"");
sb.Append(saveName);
sb.Append("\"");
sb.Append("\r\n");
sb.Append("Content-Type: ");
sb.Append("application/octet-stream");
sb.Append("\r\n");
sb.Append("\r\n");
string strPostHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);
try
{
// 根据uri创建HttpWebRequest对象
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(address));
httpReq.Method = "POST";
//对发送的数据不使用缓存
httpReq.AllowWriteStreamBuffering = false;
//设置获得响应的超时时间(300秒)
httpReq.Timeout = ;
httpReq.ServicePoint.Expect100Continue = false;
httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;
long length = fileStream.Length + postHeaderBytes.Length + boundaryBytes.Length;
long fileLength = fileStream.Length;
httpReq.ContentLength = length;
byte[] buffer = new byte[fileLength];
Stream postStream = httpReq.GetRequestStream();
//发送请求头部消息
postStream.Write(postHeaderBytes, , postHeaderBytes.Length);
int size = r.Read(buffer, , buffer.Length);
postStream.Write(buffer, , size);
//添加尾部的时间戳
postStream.Write(boundaryBytes, , boundaryBytes.Length);
postStream.Close();
//获取服务器端的响应
HttpWebResponse webRespon = (HttpWebResponse)httpReq.GetResponse();
if (webRespon.StatusCode == HttpStatusCode.OK) //如果服务器未响应,那么继续等待相应
{
Stream s = webRespon.GetResponseStream();
StreamReader sr = new StreamReader(s);
//读取服务器端返回的消息
String sReturnString = sr.ReadLine();
s.Close();
sr.Close();
fileStream.Close();
if (sReturnString == "Success")
{
returnValue = ;
}
else
{
returnValue = ;
}
}
}
catch (Exception ex)
{
returnValue = ;
}
return returnValue;
}
/// <summary>
/// 将本地文件上传到指定服务器上(HttpWebRequest方法),并传递相应参数
/// </summary>
/// <param name="url">文件上传到的服务器</param>
/// <param name="fileKeyName">类型(此处为文件--file)</param>
/// <param name="filePath">要上传的本地文件(全路径)</param>
/// <param name="filename">文件上传后的名称</param>
/// <param name="stringDict">参数集合</param>
/// <param name="timeOut">请求时效</param>
/// <returns></returns>
public static string HttpPostData(string url, string fileKeyName, string filePath, string filename, NameValueCollection stringDict, int timeOut = )
{
string responseContent;
try
{
var memStream = new MemoryStream();
var webRequest = (HttpWebRequest)WebRequest.Create(url);
// 边界符
var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
// 边界符
var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
// 最后的结束符
var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n"); // 设置属性
webRequest.Method = "POST";
webRequest.Timeout = timeOut;
webRequest.ContentType = "multipart/form-data; boundary=" + boundary; // 写入文件
const string filePartHeader = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n";
var header = string.Format(filePartHeader, fileKeyName, filename);
var headerbytes = Encoding.UTF8.GetBytes(header); memStream.Write(beginBoundary, , beginBoundary.Length);
memStream.Write(headerbytes, , headerbytes.Length); var buffer = new byte[];
int bytesRead; // =0 while ((bytesRead = fileStream.Read(buffer, , buffer.Length)) != )
{
memStream.Write(buffer, , bytesRead);
} // 写入字符串的Key
var stringKeyHeader = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"" + "\r\n\r\n{1}\r\n"; foreach (byte[] formitembytes in from string key in stringDict.Keys select string.Format(stringKeyHeader, key, stringDict[key]) into formitem select Encoding.UTF8.GetBytes(formitem))
{
memStream.Write(formitembytes, , formitembytes.Length);
} // 写入最后的结束边界符
memStream.Write(endBoundary, , endBoundary.Length); webRequest.ContentLength = memStream.Length; var requestStream = webRequest.GetRequestStream(); memStream.Position = ;
var tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, , tempBuffer.Length);
memStream.Close(); requestStream.Write(tempBuffer, , tempBuffer.Length);
requestStream.Close(); var httpWebResponse = (HttpWebResponse)webRequest.GetResponse(); using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")))
{
responseContent = httpStreamReader.ReadToEnd();
} fileStream.Close();
httpWebResponse.Close();
webRequest.Abort();
}
catch (Exception ex)
{
responseContent = ex.Message;
}
return responseContent;
} /// <summary>
/// Http下载文件支持断点续传
/// </summary>
/// <param name="uri">下载地址</param>
/// <param name="filefullpath">存放完整路径(含文件名)</param>
/// <param name="size">每次多的大小</param>
/// <returns>下载操作是否成功</returns>
public static bool HttpDownLoadFiles(string uri, string filefullpath, int size = )
{
try
{
string fileDirectory = System.IO.Path.GetDirectoryName(filefullpath);
if (!Directory.Exists(fileDirectory))
{
Directory.CreateDirectory(fileDirectory);
}
string fileFullPath = filefullpath;
string fileTempFullPath = filefullpath + ".tmp"; if (File.Exists(fileFullPath))
{
return true;
}
else
{
if (File.Exists(fileTempFullPath))
{
FileStream fs = new FileStream(fileTempFullPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); byte[] buffer = new byte[];
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri); request.Timeout = ;
request.AddRange((int)fs.Length); Stream ns = request.GetResponse().GetResponseStream(); long contentLength = request.GetResponse().ContentLength; int length = ns.Read(buffer, , buffer.Length); while (length > )
{
fs.Write(buffer, , length); buffer = new byte[]; length = ns.Read(buffer, , buffer.Length);
} fs.Close();
File.Move(fileTempFullPath, fileFullPath);
}
else
{
FileStream fs = new FileStream(fileTempFullPath, FileMode.Create); byte[] buffer = new byte[];
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Timeout = ;
request.AddRange((int)fs.Length); Stream ns = request.GetResponse().GetResponseStream(); long contentLength = request.GetResponse().ContentLength; int length = ns.Read(buffer, , buffer.Length); while (length > )
{
fs.Write(buffer, , length); buffer = new byte[]; length = ns.Read(buffer, , buffer.Length);
} fs.Close();
File.Move(fileTempFullPath, fileFullPath);
}
return true;
}
}
catch (Exception ex)
{
return false;
}
} /// <summary>
/// Http下载文件
/// </summary>
/// <param name="uri">下载地址</param>
/// <param name="filefullpath">存放完整路径(含文件名)</param>
/// <param name="size">每次多的大小</param>
/// <returns>下载操作是否成功</returns>
public static bool DownLoadFiles(string uri, string filefullpath,int size=)
{
try
{
if (File.Exists(filefullpath))
{
try
{
File.Delete(filefullpath);
}
catch (Exception ex)
{
return false;
}
}
string fileDirectory = System.IO.Path.GetDirectoryName(filefullpath);
if (!Directory.Exists(fileDirectory))
{
Directory.CreateDirectory(fileDirectory);
}
FileStream fs = new FileStream(filefullpath, FileMode.Create);
byte[] buffer = new byte[size];
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Timeout = ;
request.AddRange((int)fs.Length); Stream ns = request.GetResponse().GetResponseStream(); long contentLength = request.GetResponse().ContentLength; int length = ns.Read(buffer, , buffer.Length); while (length > )
{
fs.Write(buffer, , length); buffer = new byte[size]; length = ns.Read(buffer, , buffer.Length);
}
fs.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
}
}
C# Http访问帮助类,支持get post请求文件下载 [的更多相关文章
- HttpClient4.5 SSL访问工具类
要从网上找一个HttpClient SSL访问工具类太难了,原因是HttpClient版本太多了,稍有差别就不能用,最后笔者干脆自己封装了一个访问HTTPS并绕过证书工具类. 主要是基于新版本Http ...
- [转]DbHelper通用数据库访问帮助类
之前我一直都是在博客园中查看各位高手的博文,确实学到了不少知识,不过比较少写博客,现在就把我自己在项目实施过程中使用到比较好的技术框架写出来,希望能让更多的人了解和学习. 通常我们在开发使用数据库访问 ...
- 分享最近抽空写的一个代码生成器,集成EasyDBUtility数据库访问帮助类
一直想写一个自己的代码生成器,但是因为工作事情多,一直搁置下来,最近下决心终于利用下班时间写完了,现在分享给有需要的朋友,代码生成器集成EasyDBUtility数据库访问帮助类,暂时只支持sqlse ...
- 基于SqlSugar的开发框架循序渐进介绍(4)-- 在数据访问基类中对GUID主键进行自动赋值处理
我们在设计数据库表的时候,往往为了方便,主键ID一般采用字符串类型或者GUID类型,这样对于数据库表记录的迁移非常方便,而且有时候可以在处理关联记录的时候,提前对应的ID值.但有时候进行数据记录插入的 ...
- 小鱼提问3 static方法中可以访问某个类的私有变量吗(不通过反射的其他非正常手段)?什么情况下可以?
class Student { private string _name; public int Age = 0; public static void Test() { Student stu = ...
- Android开发调试日志工具类[支持保存到SD卡]
直接上代码: package com.example.callstatus; import java.io.File; import java.io.FileWriter; import java.i ...
- 访问祖先类的虚方法(直接访问祖先类的VMT,但是这种方法在新版本中未必可靠)
访问祖先类的虚方法 问题提出 在子类覆盖的虚方法中,可以用inherited调用父类的实现,但有时候我们并不需要父类的实现,而是想跃过父类直接调用祖先类的方法. 举个例子,假设有三个类,实现如下: t ...
- 支持异步写入的日志类,支持Framework2.0
因为工作需要需要在XP上运行一个C#编写的Winform插件,我就用Framework2.0,因为存在接口交互所以想保留交易过程的入参出参. 考虑到插件本身实施的因素,就没有使用Log4.NLog等成 ...
- WorldWind源码剖析系列:地形访问器类TerrainAccessor
地形访问器类TerrainAccessor 地形访问器类TerrainAccessor提供了对地形(高程)Terrain (elevation)访问的各种接口interface,是NltTerrain ...
随机推荐
- 导入第三方Jar包到Nexus私服
公司里面有自己的公共代码库,如果希望交给Maven进行管理,可以搭建Nexus服务器,将公司的公共代码库的代码打成jar包,然后上传到Nexus私服服务器上,项目组的成员就可以在Maven项目中通过添 ...
- ffmpeg抓屏输出的设置
之前做windows下抓屏输出时使用ffmpeg.exe作为抓屏输出测试,命令行如下: ffmpeg -f gdigrab -i "desktop" -r 25 -vcodec m ...
- 【转】Pycharm创建py文件时自定义头部模板
File->settings->Editor->File and Code Templates->Python Script #!/usr/bin/env python # - ...
- 关于Python中深拷贝与浅拷贝的理解(一)---概念
import copy a = [1, 2, 3, 4, ['a', 'b']] #原始对象 b = a #赋值,传对象的引用 c = copy.copy(a) #对象拷贝,浅拷贝 d = copy. ...
- Android开发(三十)——ScrollView中ListView的高度自动适应
int totalHeight = 0; for (int i = 0; i < mStrings.length; i++) { //pullList ListView //mAdapter A ...
- 遍历目录下的所有文件-os.walk
#coding:utf-8 import os for root,dirs,files in os.walk("D:"): for fileItem in files: print ...
- Eclipse源代码分析
Eclipse源代码分析 一.概述走入Eclipse的内核,看看它到底是怎么工作的? 1.Eclipse源代码 下载地址:http://download.eclipse.org/eclipse/dow ...
- SpringMVC RedirectView的使用以及源码分析
看一段普通的代码,我们访问controller中的一个方法后,重定向到另外一个controller或者视图. @RequestMapping(params="method=index&quo ...
- C#中[] 、List、Array、ArrayList等数据结构的差异简述
[] 是针对特定类型.固定长度的. List 是针对特定类型.任意长度的. Array 是针对任意类型.固定长度的. ArrayList 是针对任意类型.任意长度的. Array 和 ArrayLis ...
- 1.php代码块
一.登录 <form action="index.php?m=admin&c=index&a=login&dosubmit=1" method=&qu ...