HttpHelper类处理两种HTTP POST请求

csharp 复制代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Common
{
    public static class HttpHelper
    {
        public static string PostJson(string url, string json, Dictionary<string, string> headers = null)
        {
            // 创建请求对象
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json";

            if (headers != null)
            {
                foreach (var header in headers)
                {
                    if (string.Equals(header.Key, "Accept", StringComparison.OrdinalIgnoreCase))
                    {
                        request.Accept = header.Value;
                    }
                    else if (string.Equals(header.Key, "User-Agent", StringComparison.OrdinalIgnoreCase))
                    {
                        request.UserAgent = header.Value;
                    }
                    else if (string.Equals(header.Key, "Content-Type", StringComparison.OrdinalIgnoreCase))
                    {
                        request.ContentType = header.Value;
                    }
                    else
                    {
                        request.Headers[header.Key] = header.Value;
                    }
                }
            }

            // 序列化数据
            byte[] postBytes = Encoding.UTF8.GetBytes(json);

            // 写入请求体
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(postBytes, 0, postBytes.Length);
            }

            // 获得响应
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                {
                    return sr.ReadToEnd();
                }
            }
        }

        public static string PostMutipartFormData(string url, string jsonData, List<Files> files, Dictionary<string, string> headers = null)
        {
            // 创建请求对象
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.KeepAlive = true;
            request.Accept = "application/json";

            // 设置请求头
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    if (string.Equals(header.Key, "Accept", StringComparison.OrdinalIgnoreCase))
                    {
                        request.Accept = header.Value;
                    }
                    else if (string.Equals(header.Key, "User-Agent", StringComparison.OrdinalIgnoreCase))
                    {
                        request.UserAgent = header.Value;
                    }
                    else if (string.Equals(header.Key, "Content-Type", StringComparison.OrdinalIgnoreCase))
                    {
                        request.ContentType = header.Value;
                    }
                    else
                    {
                        request.Headers[header.Key] = header.Value;
                    }
                }
            }

            // 写入请求体
            // 生成随机边界分隔符
            string boundary = "---" + DateTime.Now.Ticks.ToString("x");
            request.ContentType = "multipart/form-data;boundary=" + boundary;

            string retMsg = string.Empty;

            using (Stream requestStream = request.GetRequestStream())
            using (StreamWriter write = new StreamWriter(requestStream))
            {
                // 添加json部分
                write.WriteLine($"--{boundary}");
                write.WriteLine($"Content-Disposition: form-data;name=\"refundDatasas\"");
                write.WriteLine($"Content-Type:application/json");
                write.WriteLine(jsonData);
                write.Flush();

                // 添加文件部分
                foreach (var file in files)
                {
                    var bt = Encoding.UTF8.GetBytes(file.fileStream);
                    write.WriteLine($"--{boundary}");
                    write.WriteLine($"Content-Disposition: form-data;name=\"files\";filename=\"{file.fileName}\"");
                    write.WriteLine($"Content-Type: " + GetMimeType(file.fileName));
                    write.WriteLine();
                    write.Flush();

                    requestStream.Write(bt, 0, bt.Length);
                    write.WriteLine();
                    write.Flush();
                }

                //结束边界
                write.WriteLine($"--{boundary}-");
                write.Flush();
            }

            try
            {
                //获得响应
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    Console.WriteLine($"Status:{response.StatusCode}");
                    //读取响应内容
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        var responseBody = reader.ReadToEnd();
                        retMsg = responseBody;
                        Console.WriteLine($"Response:{responseBody}");
                    }
                }
            }
            catch (WebException ex)
            {
                if (ex.Response is HttpWebResponse errorResponse)
                {
                    Console.WriteLine($"HTTP Error:{errorResponse.StatusCode}");
                    using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                    {
                        var responseBody = reader.ReadToEnd();
                        retMsg = responseBody;
                        Console.WriteLine($"Error details:{responseBody}");
                    }
                }
                else
                {
                    Console.WriteLine($"Network Error:{ex.Message}");
                }
            }

            return retMsg;
        }

        private static string GetMimeType(string fileName)
        {
            var extension = Path.GetFileName(fileName).ToLowerInvariant();

            switch (extension)
            {
                case ".png": return "image/png";
                case ".jpg":
                case ".jpeg": return "image/jpeg";
                case ".pdf": return "application/pdf";
                default: return "application/octet-stream";
            }
        }
    }
}
相关推荐
Eiceblue21 分钟前
使用 C# 发送电子邮件(支持普通文本、HTML 和附件)
开发语言·c#·html·visual studio
小小小小王王王26 分钟前
hello判断
开发语言·c#
金增辉2 小时前
基于C#的OPCServer应用开发,引用WtOPCSvr.dll
c#
future14124 小时前
C#学习日记
开发语言·学习·c#
傻啦嘿哟5 小时前
Python 办公实战:用 python-docx 自动生成 Word 文档
开发语言·c#
唐青枫10 小时前
C#.NET log4net 详解
c#·.net
lijingguang1 天前
在C#中根据URL下载文件并保存到本地,可以使用以下方法(推荐使用现代异步方式)
开发语言·c#
¥-oriented1 天前
【C#中路径相关的概念】
开发语言·c#
ArabySide1 天前
【WCF】通过AOP实现基于JWT的授权与鉴权的实践
c#·jwt·aop·wcf