c# http方法工具类整合

using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Collections.Generic;

public class HttpUtil
{
    /// <summary>
    /// 通用http方法
    /// </summary>
    /// <param name="url">请求地址</param>
    /// <param name="postData">发送的数据</param>
    /// <param name="encoding">发送的编码格式</param>
    /// <param name="contentType">内容类型,取值推荐从本工具类的"HttpContentType"中取</param>
    /// <param name="postType">发送类型</param>
    /// <param name="headDic">头字典</param>
    /// <returns></returns>
    public static string HttpMethod(string url, string postData, Encoding encoding, string contentType, PostType postType, Dictionary<string, string> headDic)
    {
        if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
        {
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
        }
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = postType.ToString();
        request.Accept = "*/*";
        request.ContentType = contentType;
        request.Credentials = CredentialCache.DefaultCredentials;
        //用户标识一定要加,不然有些严一点的网站会返回错误信息,比如说微信的,不按照规范来,很容易403
        request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; QQWubi 133; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; CIBA; InfoPath.2)";
        request.ProtocolVersion = HttpVersion.Version10;

        //添加请求头
        if (headDic != null && headDic.Count > 0)
        {
            Dictionary<string, string>.Enumerator it = headDic.GetEnumerator();
            while (it.MoveNext())
            {
                request.Headers.Add(it.Current.Key, it.Current.Value);
            }
        }

        if (!string.IsNullOrEmpty(postData))
        {
            byte[] buffer = encoding.GetBytes(postData);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
        }

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        try
        {
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
            {
                return reader.ReadToEnd();
            }
        }
        catch (WebException ex)
        {
            //这一步很有必要,因为有的地方会把错误信息放在异常里面,但是直接ex.message是看不到具体信息的,只有显示403拒绝访问
            response = (HttpWebResponse)ex.Response;
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
            {
                return reader.ReadToEnd();
            }
        }
        finally
        {
            response.Close();
        }
    }

    /// <summary>
    /// httprequest的formdata传参
    /// </summary>
    /// <param name="url"></param>
    /// <param name="postData">存放字符串参数的键值对</param>
    /// <param name="fileData">存放文件参数的键值对 参数名,文件完整路径</param>
    /// <param name="encoding">字符编码</param>
    /// <param name="postType">发送方式</param>
    /// <param name="headDic">请求头,根据需求来,可为空</param>
    /// <returns></returns>
    public static string HttpMethod(string url, Dictionary<string, string> postData, Dictionary<string, string> fileData, Encoding encoding, PostType postType, Dictionary<string, string> headDic)
    {
        if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
        {
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
        }

        string strBoundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = postType.ToString();
        request.Accept = "*/*";
        request.ContentType = "multipart/form-data;boundary=" + strBoundary;
        request.Credentials = CredentialCache.DefaultCredentials;
        //用户标识一定要加,不然有些严一点的网站会返回错误信息,比如说微信的,不按照规范来,很容易403
        request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; QQWubi 133; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; CIBA; InfoPath.2)";
        request.ProtocolVersion = HttpVersion.Version10;

        //添加请求头
        if (headDic != null && headDic.Count > 0)
        {
            Dictionary<string, string>.Enumerator it = headDic.GetEnumerator();
            while (it.MoveNext())
            {
                request.Headers.Add(it.Current.Key, it.Current.Value);
            }
        }

        Stream myRequestStream = request.GetRequestStream();

        //组成普通参数信息
        foreach (KeyValuePair<string, string> item in postData)
        {
            StringBuilder strBPostContent = new StringBuilder();
            strBPostContent.Append("--" + strBoundary + "\r\n");
            strBPostContent.Append("Content-Disposition: form-data; name=\"" + item.Key + "\"\r\n");
            strBPostContent.Append("\r\n" + item.Value + "\r\n");
            byte[] byteArrPostContent = encoding.GetBytes(strBPostContent.ToString());
            myRequestStream.Write(byteArrPostContent, 0, byteArrPostContent.Length);//写入参数
        }

        //处理文件参数信息
        foreach (KeyValuePair<string, string> item in fileData)
        {
            string filename = Path.GetFileName(item.Value);//获取文件名
            StringBuilder strBFileContent = new StringBuilder();
            strBFileContent.Append("--" + strBoundary + "\r\n");
            strBFileContent.Append("Content-Disposition:form-data; name=\"" + item.Key + "\";filename=\"" + filename + "\"" + "\r\n\r\n");
            byte[] byteArrFileContent = encoding.GetBytes(strBFileContent.ToString());
            myRequestStream.Write(byteArrFileContent, 0, byteArrFileContent.Length);//写入文件信息

            //读取文件信息
            FileStream fileStream = new FileStream(item.Value, FileMode.Open, FileAccess.Read, FileShare.Read);
            byte[] bytes = new byte[fileStream.Length];
            fileStream.Read(bytes, 0, bytes.Length);
            fileStream.Close();
            byte[] UpdateFile = bytes;//转换为二进制
            if (UpdateFile.Length == 0)
            {
                return "file error";
            }
            myRequestStream.Write(UpdateFile, 0, UpdateFile.Length);//文件写入请求流中
        }
        //请求体末尾
        byte[] byteArrContentEnd = encoding.GetBytes("\r\n--" + strBoundary + "--\r\n");
        myRequestStream.Write(byteArrContentEnd, 0, byteArrContentEnd.Length);//写入结尾
        myRequestStream.Close();

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        try
        {
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
            {
                return reader.ReadToEnd();
            }
        }
        catch (WebException ex)
        {
            //这一步很有必要,因为有的地方会把错误信息放在异常里面,但是直接ex.message是看不到具体信息的,只有显示403拒绝访问
            response = (HttpWebResponse)ex.Response;
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
            {
                return reader.ReadToEnd();
            }
        }
        finally
        {
            response.Close();
        }
    }


    /// <summary>
    /// 请求类型
    /// </summary>
    public enum PostType
    {
        POST,
        GET
    }

    /// <summary>
    /// HTTP 内容类型(Content-Type)
    /// </summary>
    public class HttpContentType
    {
        /// <summary>
        /// 资源类型:普通文本
        /// </summary>
        public const string TEXT_PLAIN = "text/plain";

        /// <summary>
        /// 资源类型:JSON字符串
        /// </summary>
        public const string APPLICATION_JSON = "application/json";

        /// <summary>
        /// 资源类型:未知类型(数据流)
        /// </summary>
        public const string APPLICATION_OCTET_STREAM = "application/octet-stream";

        /// <summary>
        /// 资源类型:表单数据(键值对)
        /// </summary>
        public const string WWW_FORM_URLENCODED = "application/x-www-form-urlencoded";

        /// <summary>
        /// 资源类型:表单数据(键值对)。编码方式为 gb2312
        /// </summary>
        public const string WWW_FORM_URLENCODED_GB2312 = "application/x-www-form-urlencoded;charset=gb2312";

        /// <summary>
        /// 资源类型:表单数据(键值对)。编码方式为 utf-8
        /// </summary>
        public const string WWW_FORM_URLENCODED_UTF8 = "application/x-www-form-urlencoded;charset=utf-8";

        /// <summary>
        /// 资源类型:多分部数据
        /// </summary>
        public const string MULTIPART_FORM_DATA = "multipart/form-data";
    }

    private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
    {
        return true; //总是接受
    }
}

 

 

posted on 2021-02-05 10:35  炼金师  阅读(1081)  评论(0编辑  收藏  举报

导航