C# http帮助类

来源:互联网 发布:北京python培训班 编辑:程序博客网 时间:2024/05/16 11:45


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NotifyWebApi.Models;
using System.Net;
using System.IO;
using System.Text;

namespace NotifyWebApi.Utils
{
    public class CHttpUtil
    {
        HttpWebRequest m_Request;
        HttpWebResponse m_Response;
        CNotifyBase m_notifyBase;

        public CHttpUtil()
        {
            if(m_notifyBase == null)
            {
                m_notifyBase = new CNotifyBase();
            }
        }

        public string SendRcv(string msg, HttpHeaderIn httpSenderIn)
        {
            return SendRcv(Encoding.UTF8, msg, httpSenderIn);
        }

        public string SencRcvUpload( HttpHeaderIn httpSenderIn, string filePath,string fileName)
        {
            return SendRcvUpload(Encoding.UTF8, httpSenderIn, filePath, fileName);
        }

        public string SendRcvUpload(Encoding encoder, HttpHeaderIn httpSenderIn, string filePath,string fileName)
        {
            string response = string.Empty;

            if (!ValidParams(httpSenderIn))
            {
                return null;
            }

            m_notifyBase.LogInfo("Url:" + httpSenderIn.Url);
            //m_notifyBase.LogInfo("Method:" + httpSenderIn.Method);
            //m_notifyBase.LogInfo("ContentType:" + httpSenderIn.ContentType);
            //m_notifyBase.LogInfo("Msg:" + msg);

            MemoryStream memStream = null;
            FileStream fileStream = null;
            HttpWebRequest webRequest = null;
            HttpWebResponse httpWebResponse = null;

            try
            {
                var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
                var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
                fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

                // 最后的结束符
                var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");
                byte[] enterER = Encoding.ASCII.GetBytes("\r\n");

                //// 文件参数头
                const string filePartHeader =
                "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
                "Content-Type: application/octet-stream\r\n\r\n";
                var fileHeader = string.Format(filePartHeader, "media", fileName);
                var fileHeaderBytes = encoder.GetBytes(filePartHeader);

                // 开始拼数据
                memStream = new MemoryStream();
                memStream.Write(beginBoundary, 0, beginBoundary.Length);

                // 文件数据
                memStream.Write(fileHeaderBytes, 0, fileHeaderBytes.Length);

                var buffer = new byte[1024];
                int bytesRead; // =0
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    memStream.Write(buffer, 0, bytesRead);
                }

                memStream.Write(enterER, 0, enterER.Length); //添加\r\n

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

                //倒腾到tempBuffer
                memStream.Position = 0;
                var tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);

                // 创建webRequest并设置属性
                webRequest = (HttpWebRequest)WebRequest.Create(httpSenderIn.Url);
                webRequest.Method = httpSenderIn.Method.ToUpper();
                webRequest.Timeout = httpSenderIn.TimeOut;
                webRequest.ContentType = httpSenderIn.ContentType + ";boundary=" + boundary;
                //webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
                webRequest.ContentLength = tempBuffer.Length;

                var requestStream = webRequest.GetRequestStream();
                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                requestStream.Close();

                httpWebResponse = (HttpWebResponse)webRequest.GetResponse();

                using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")))
                {
                    response = httpStreamReader.ReadToEnd();
                }
            }
            catch(Exception e)
            {
                m_notifyBase.LogErr(e.Message);
                m_notifyBase.LogErr("\n");
                m_notifyBase.LogErr(e.StackTrace);
                response = null;
            }

            if (fileStream != null)
            {
                fileStream.Close();
            }

            if (memStream != null)
            {
                memStream.Close();
            }

            if (httpWebResponse != null)
            {
                httpWebResponse.Close();
            }

            if (webRequest != null)
            {
                webRequest.Abort();
            }

            return response;
        }

        public string SendRcv(Encoding encoder, string msg, HttpHeaderIn httpSenderIn)
        {
            string response = string.Empty;

            if (!ValidParams(httpSenderIn))
            {
                return null;
            }

            m_notifyBase.LogInfo("Url:" + httpSenderIn.Url);
            //m_notifyBase.LogInfo("Method:" + httpSenderIn.Method);
            //m_notifyBase.LogInfo("ContentType:" + httpSenderIn.ContentType);
            m_notifyBase.LogInfo("Msg:" + msg);

            try
            {
                long nLen = 0;
                byte[] bData = null;

                if (!string.IsNullOrEmpty(msg))
                {
                    bData = encoder.GetBytes(msg);
                    nLen = bData.Length;
                }

                m_Request = (HttpWebRequest)WebRequest.Create(httpSenderIn.Url);
                m_Request.Method = httpSenderIn.Method;
                m_Request.ContentType = httpSenderIn.ContentType;
                m_Request.ContentLength = nLen;

                if (nLen > 0)
                {
                    Stream write = m_Request.GetRequestStream();
                    write.Write(bData, 0, bData.Length);
                    write.Close();
                }

                m_Response = (HttpWebResponse)m_Request.GetResponse();

                using (var httpStreamReader = new StreamReader(m_Response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
                {
                    response = httpStreamReader.ReadToEnd();
                }
               
                m_Request.Abort();
            }
            catch (Exception e)
            {
                m_notifyBase.LogErr(e.Message);
                m_notifyBase.LogErr(e.StackTrace);
                return null;
            }

            return response;
        }
       
        private bool ValidParams(HttpHeaderIn httpSenderIn)
        {
            if (string.IsNullOrEmpty(httpSenderIn.Url) || string.IsNullOrEmpty(httpSenderIn.Url))
            {
                m_notifyBase.LogErr("Url为空");
                return false;
            }

            if (string.IsNullOrEmpty(httpSenderIn.Method) || string.IsNullOrEmpty(httpSenderIn.Method))
            {
                m_notifyBase.LogErr("Method为空");
                return false;
            }

            if (string.IsNullOrEmpty(httpSenderIn.ContentType) || string.IsNullOrEmpty(httpSenderIn.ContentType))
            {
                m_notifyBase.LogErr("ContentType为空");
                return false;
            }

            return true;
        }
    }
}

原创粉丝点击