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";
            }
        }
    }
}
相关推荐
上位机付工5 小时前
C#与倍福TwinCAT3进行ADS通信
开发语言·c#
土了个豆子的6 小时前
02.继承MonoBehaviour的单例模式基类
开发语言·visualstudio·单例模式·c#·里氏替换原则
疯狂的维修6 小时前
c#中public类比博图
c#·自动化
土了个豆子的8 小时前
03.缓存池
开发语言·前端·缓存·visualstudio·c#
xiaowu0801 天前
策略模式-不同的鸭子的案例
开发语言·c#·策略模式
VisionPowerful1 天前
九.弗洛伊德(Floyd)算法
算法·c#
ArabySide1 天前
【C#】 资源共享和实例管理:静态类,Lazy<T>单例模式,IOC容器Singleton我们该如何选
单例模式·c#·.net core
gc_22991 天前
C#测试调用OpenXml操作word文档的基本用法
c#·word·openxml
almighty271 天前
C#海康车牌识别实战指南带源码
c#·海康车牌识别·c#实现车牌识别·车牌识别源码·c#车牌识别
c#上位机2 天前
wpf之TextBlock
c#·wpf