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, 0, 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 = 300000;
                                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 = 300000;
                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") > -1)
                {
                    return false;
                }
                else
                {
                    FileStream fs = new FileStream(filePath, FileMode.Create);
                    var buff = Encoding.UTF8.GetBytes(responseContent);
                    fs.Write(buff, buff.Length, 0);
                    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 0;
                                }
                                FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
                                return Upload_Request(address, fs, saveName);
                        }
                        catch (Exception ex)
                        {
                                return 0;
                        }
                }

                /// <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 = 0;
                        fileStream.Position = 0;
                        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 = 300000;
                                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, 0, postHeaderBytes.Length);
                                int size = r.Read(buffer, 0, buffer.Length);
                                postStream.Write(buffer, 0, size);
                                //添加尾部的时间戳
                                postStream.Write(boundaryBytes, 0, 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 = 1;
                                        }
                                        else
                                        {
                                                returnValue = 0;
                                        }
                                }
                        }
                        catch (Exception ex)
                        {
                                returnValue = 0;
                        }
                        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 = 900000)
                {
                        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, 0, beginBoundary.Length);
                                memStream.Write(headerbytes, 0, headerbytes.Length);

                                var buffer = new byte[1024];
                                int bytesRead; // =0

                                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                                {
                                        memStream.Write(buffer, 0, 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, 0, formitembytes.Length);
                                }

                                // 写入最后的结束边界符
                                memStream.Write(endBoundary, 0, endBoundary.Length);

                                webRequest.ContentLength = memStream.Length;

                                var requestStream = webRequest.GetRequestStream();

                                memStream.Position = 0;
                                var tempBuffer = new byte[memStream.Length];
                                memStream.Read(tempBuffer, 0, tempBuffer.Length);
                                memStream.Close();

                                requestStream.Write(tempBuffer, 0, 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 = 1024)
                {
                        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[512];
                                                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);

                                                request.Timeout = 10000;
                                                request.AddRange((int)fs.Length);

                                                Stream ns = request.GetResponse().GetResponseStream();

                                                long contentLength = request.GetResponse().ContentLength;

                                                int length = ns.Read(buffer, 0, buffer.Length);

                                                while (length > 0)
                                                {
                                                        fs.Write(buffer, 0, length);

                                                        buffer = new byte[512];

                                                        length = ns.Read(buffer, 0, buffer.Length);
                                                }

                                                fs.Close();
                                                File.Move(fileTempFullPath, fileFullPath);
                                        }
                                        else
                                        {
                                                FileStream fs = new FileStream(fileTempFullPath, FileMode.Create);

                                                byte[] buffer = new byte[512];
                                                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
                                                request.Timeout = 10000;
                                                request.AddRange((int)fs.Length);

                                                Stream ns = request.GetResponse().GetResponseStream();

                                                long contentLength = request.GetResponse().ContentLength;

                                                int length = ns.Read(buffer, 0, buffer.Length);

                                                while (length > 0)
                                                {
                                                        fs.Write(buffer, 0, length);

                                                        buffer = new byte[512];

                                                        length = ns.Read(buffer, 0, 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=1024)
        {
            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 = 10000;
                request.AddRange((int)fs.Length);

                Stream ns = request.GetResponse().GetResponseStream();

                long contentLength = request.GetResponse().ContentLength;

                int length = ns.Read(buffer, 0, buffer.Length);

                while (length > 0)
                {
                    fs.Write(buffer, 0, length);

                    buffer = new byte[size];

                    length = ns.Read(buffer, 0, buffer.Length);
                }
                fs.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        }
}
时间: 2024-10-11 06:44:02

C# Http访问帮助类,支持get post请求文件下载 [的相关文章

分享最近抽空写的一个代码生成器,集成EasyDBUtility数据库访问帮助类

一直想写一个自己的代码生成器,但是因为工作事情多,一直搁置下来,最近下决心终于利用下班时间写完了,现在分享给有需要的朋友,代码生成器集成EasyDBUtility数据库访问帮助类,暂时只支持sqlserver数据库,界面如下 部分代码如下 using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Te

Spring Boot如何让某个Controller支持跨源请求,以及如何让Controller类某个成员方法支持跨源请求

在前面我们已经讨论了Spring Boot 如何全局支持跨源请求.如果你想了解可以查看这篇文章 下面我们讨论另一种场景.有些时候,你需要让你的应用在大部分的时候,仅仅支持当前域名下的请求.而仅仅在极其特殊的几个场合下,才支持跨源请求.这个时候,你需要把跨源请求仅仅缩小在几个Controller上,或者Controller类的几个成员方法上.这个时候你需要用到如下的注解:@CrossOrigin(origins = "*", maxAge = 3600) .把这个注解放到 Control

django之创建第4-2个项目-访问class类属性和类方法

1.修改index <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>django之创建第4-2个项目</title> </head> <body> <h1>hello,{{test.name}}</h1> <!--模板 变量用变量定义--> &l

访问祖先类的虚方法(直接访问祖先类的VMT,但是这种方法在新版本中未必可靠)

访问祖先类的虚方法 问题提出 在子类覆盖的虚方法中,可以用inherited调用父类的实现,但有时候我们并不需要父类的实现,而是想跃过父类直接调用祖先类的方法. 举个例子,假设有三个类,实现如下: type TClassA = class procedure Proc; virtual; end; TClassB = class(TClassA) procedure Proc; override; end; TClassC = class(TClassB) procedure Proc; ove

1.27 Java基础总结 ①访问修饰符访问权限②类和方法的基本声明和使用1.27 Java基础总结 ①访问修饰符访问权限②类和方法的基本声明和使用

1.27 Java基础总结 ①访问修饰符访问权限②类和方法的基本声明和使用 成员变量(属性)①类中添加成员变量 访问修饰符 类型 变量名 private String name ②实例化对象调用类的构造方法类构造对象,Teacher one = new Teacher(): 有static的可以直接调用,因为static是类级别的 ③JavaBean里边一般规则应该有公共的无参构造应该有符合命名规范的get/set方法 ④对象的回收:没有任何引用指向该对象时,GC会回收 主动回收:对象 = nu

C#---数据库访问通用类、Access数据库操作类、mysql类 .[转]

原文链接 //C# 数据库访问通用类 (ADO.NET)using System;using System.Collections.Generic;using System.Text;using System.Data;using System.Data.SqlClient;using System.Configuration; namespace XXX{    /// <summary>    /// 针对SQL Server数据库操作的通用类           /// </sum

C++的继承操作---基类指针访问派生类问题---基类成员恢复访问属性问题

#include "stdafx.h" #include <iostream> #include <algorithm> using namespace std; class Base { public: int num; virtual void func() { cout<<"Do something in Base"<<endl; } }; class Derived:private Base { public:

WorldWind源码剖析系列:地形访问器类TerrainAccessor

地形访问器类TerrainAccessor提供了对地形(高程)Terrain (elevation)访问的各种接口interface,是NltTerrainAccessor类的基类.该类类图如下. 基类TerrainAccessor提供的主要处理方法简要描述如下: protected string m_name; //地形模型名称 protected double m_north; //地形北部边界 protected double m_south; //地形南部边界 protected dou

关于“在本类中访问本类私有静态变量”的一点疑惑解析

关于"在本类中访问本类私有静态变量"的一点疑惑解析 代码如下: public class StaticVar { private static int x = 100; public static void main(String[] args) { StaticVar var1 = new StaticVar(); var1.x++; StaticVar var2 = new StaticVar(); var2.x++; StaticVar.x++; System.out.print