代码如下,支持POST/PUT/GET/RAW/TXT/JSON等请求方式上传文件的同时一并提交参数


public class Network
{
    /// <summary>
    /// 发起请求请求表单形式可提交文件与参数
    /// </summary>
    /// <param name=”Url”>请求地址</param>
    /// <param name=”Method”>请求方式</param>
    /// <param name=”Param”>参数</param>
    /// <param name=”Headers”>Header</param>
    /// <param name=”ContentType”>类型</param>
    /// <returns></returns>
    public static string HttpRequest(string Url, string Method = “POST”, List<FormParam> Param = null, List<Header> Headers = null, string ContentType = “”)
    {
        if (Method == “GET”)
        {
            if (Param != null && Param.Count > 0)
            {
                foreach (var item in Param)
                {
                    string param = “”;
                    if (Url.Contains(“?”))
                    {
                        param = “&”;
                    }
                    else
                    {
                        param = “?”;
                    }
                    param += string.Format(“{0}={1}”, UrlEncode(item.Name), UrlEncode(item.Value));
                    Url += param;
                }
            }
        }
        string Boundary = Guid.NewGuid().ToString();
        byte[] BoundaryBytes = Encoding.ASCII.GetBytes(“\r\n–” + Boundary + “\r\n”);
        byte[] EndBoundaryBytes = Encoding.ASCII.GetBytes(“\r\n–” + Boundary + “–\r\n”);
        HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(Url);
        Request.ContentType = string.Format(“{0};boundary={1}”, ContentType, Boundary);
        Request.Method = Method;
        Request.KeepAlive = true;
        Request.Accept = “*/*”;
        Request.KeepAlive = true;
        Request.Headers.Add(“Accept-Encoding”, “gzip, deflate, br”);
        Request.Headers.Add(“Connection”, “keep-alive”);
        if (Headers != null && Headers.Count > 0)
        {
            foreach (var item in Headers)
            {
                Request.Headers.Add(item.Name, item.Value);
            }
        }
        // 普通参数模板
        string FormDataTemplate = “Content-Disposition: form-data; name=\”{0}\”\r\n\r\n{1}”;
        //带文件的参数模板
        string FileFormDataTemplate = “Content-Disposition: form-data; name=\”{0}\”; filename=\”{1}\”\r\n”;
        FileFormDataTemplate += “Content-Type: {2}\r\n\r\n”;
        using (Stream RequestStream = Request.GetRequestStream())
        {
            if (Param != null && Param.Count > 0)
            {
                foreach (var item in Param)
                {
                    RequestStream.Write(BoundaryBytes, 0, BoundaryBytes.Length);
                    byte[] WriteBytes;
                    if (item.Type == “file”)
                    {
                        WriteBytes = Encoding.UTF8.GetBytes(string.Format(FileFormDataTemplate, item.Name, item.Value, “application/octet-stream”));
                        RequestStream.Write(WriteBytes, 0, WriteBytes.Length);
                        using (var FileStream = new FileStream(item.Value, FileMode.Open, FileAccess.Read))
                        {
                            byte[] Buffer = new byte[2096];
                            int BytesRead = 0;
                            while ((BytesRead = FileStream.Read(Buffer, 0, Buffer.Length)) != 0)
                            {
                                RequestStream.Write(Buffer, 0, BytesRead);
                            }
                        }
                    }
                    else
                    {
                        WriteBytes = Encoding.UTF8.GetBytes(string.Format(FormDataTemplate, item.Name, item.Value));
                        RequestStream.Write(WriteBytes, 0, WriteBytes.Length);
                    }
                }
            }
            RequestStream.Write(EndBoundaryBytes, 0, EndBoundaryBytes.Length);
        }
        HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
        Stream ReceiveStream = Response.GetResponseStream();
        StreamReader ReadStream = new StreamReader(ReceiveStream, Encoding.GetEncoding(“utf-8”));
        string RetText = ReadStream.ReadToEnd();
        Response.Close();
        ReadStream.Close();
        return RetText;
    }
    /// <summary>
    /// POST 请求RAW形式提交支持 json/xml/text
    /// </summary>
    /// <param name=”Url”>请求地址</param>
    /// <param name=”ContentType”>类型</param>
    /// <param name=”Method”>请求方式</param>
    /// <param name=”Param”>参数</param>
    /// <param name=”Headers”>Header</param>
    /// <returns></returns>
    public static string PostRaw(string Url, string ContentType, string Method = “POST”, string Param = null, List<Header> Headers = null)
    {
        string Boundary = Guid.NewGuid().ToString();
        HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(Url);
        Request.ContentType = string.Format(“{0};boundary={1}”, ContentType, Boundary);
        Request.Method = Method;
        Request.KeepAlive = true;
        Request.Accept = “*/*”;
        Request.KeepAlive = true;
        Request.Headers.Add(“Accept-Encoding”, “gzip, deflate, br”);
        Request.Headers.Add(“Connection”, “keep-alive”);
        if (Headers != null && Headers.Count > 0)
        {
            foreach (var item in Headers)
            {
                Request.Headers.Add(item.Name, item.Value);
            }
        }
        using (Stream RequestStream = Request.GetRequestStream())
        {
            if (Param != null && Param != “”)
            {
                byte[] WriteBytes = Encoding.UTF8.GetBytes(Param);
                RequestStream.Write(WriteBytes, 0, WriteBytes.Length);
            }
        }
        HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
        Stream ReceiveStream = Response.GetResponseStream();
        StreamReader ReadStream = new StreamReader(ReceiveStream, Encoding.GetEncoding(“utf-8”));
        string RetText = ReadStream.ReadToEnd();
        Response.Close();
        ReadStream.Close();
        return RetText;
    }
    /// <summary>
    /// POST 请求二进制形式提交
    /// </summary>
    /// <param name=”Url”>请求地址</param>
    /// <param name=”Method”>请求方式</param>
    /// <param name=”Param”>文件路径</param>
    /// <param name=”Headers”>Header</param>
    /// <returns></returns>
    public static string HttpRequestBinaryRaw(string Url, string Method = “POST”, string[] FilePath = null, List<Header> Headers = null)
    {
        string Boundary = Guid.NewGuid().ToString();
        HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(Url);
        Request.ContentType = string.Format(“{0};boundary={1}”, “application/octet-stream”, Boundary);
        Request.Method = Method;
        Request.KeepAlive = true;
        Request.Accept = “*/*”;
        Request.KeepAlive = true;
        Request.Headers.Add(“Accept-Encoding”, “gzip, deflate, br”);
        Request.Headers.Add(“Connection”, “keep-alive”);
        if (Headers != null && Headers.Count > 0)
        {
            foreach (var item in Headers)
            {
                Request.Headers.Add(item.Name, item.Value);
            }
        }
        using (Stream RequestStream = Request.GetRequestStream())
        {
            if (FilePath != null && FilePath.Length > 0)
            {
                foreach (var item in FilePath)
                {
                    FileStream Fs = new FileStream(item, FileMode.Open);
                    BinaryReader Binary = new BinaryReader(Fs);
                    Byte[] WriteBytes = Binary.ReadBytes((int)Fs.Length);
                    Fs.Close();
                    RequestStream.Write(WriteBytes, 0, WriteBytes.Length);
                }
            }
        }
        HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
        Stream ReceiveStream = Response.GetResponseStream();
        StreamReader ReadStream = new StreamReader(ReceiveStream, Encoding.GetEncoding(“utf-8”));
        string RetText = ReadStream.ReadToEnd();
        Response.Close();
        ReadStream.Close();
        return RetText;
    }
    /// <summary>
    /// 进行URL编码
    /// </summary>
    /// <param name=”Str”></param>
    /// <returns></returns>
    public static string UrlEncode(string Str)
    {
        StringBuilder Sb = new StringBuilder();
        byte[] byStr = Encoding.UTF8.GetBytes(Str);
        for (int i = 0; i < byStr.Length; i++)
        {
            Sb.Append(@”%” + Convert.ToString(byStr[i], 16));
        }
        return (Sb.ToString());
    }
}
public class FormParam
{
    private string _Name;
    private string _Value;
    private string _Type;
    public FormParam()
    {
    }
    public FormParam(string Name)
    {
        this._Name = Name;
    }
    public FormParam(string Name, string Value)
    {
        this._Name = Name;
        this._Value = Value;
    }
    public FormParam(string Name, string Value, string Type)
    {
        this._Name = Name;
        this._Value = Value;
        this._Type = Type;
    }
    public string Name
    {
        get { return _Name; }
        set { _Name = value; }
    }
    public string Value
    {
        get { return _Value; }
        set { _Value = value; }
    }
    public string Type
    {
        get { return _Type; }
        set { _Type = value; }
    }
}
public class Header
{
    private string _Name;
    private string _Value;
    public Header()
    {
    }
    public Header(string Name)
    {
        this._Name = Name;
    }
    public Header(string Name, string Value)
    {
        this._Name = Name;
        this._Value = Value;
    }
    public string Name
    {
        get { return _Name; }
        set { _Name = value; }
    }
    public string Value
    {
        get { return _Value; }
        set { _Value = value; }
    }
}
说点什么
支持Markdown语法
在"C# 模拟HTTP请求帮助类,支持POST/PUT/GET/RAW/TXT/JSON等请求方式上传文件的同时一并提交参数"已有1条评论
Loading...