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";
            }
        }
    }
}
相关推荐
流水线上的指令侠10 小时前
使用C#写微信小程序后端——电商微信小程序
微信小程序·小程序·c#·visual studio
gc_229912 小时前
C#编写的WebApi接口直接返回byte数组引发的问题
c#·byte数组
刘梦凡呀1 天前
C#获取钉钉平台考勤记录
java·c#·钉钉
承渊政道1 天前
动态内存管理
c语言·c++·经验分享·c#·visual studio
future_studio1 天前
聊聊 Unity(小白专享、C# 小程序 之 播放器)
unity·小程序·c#
helloworddm1 天前
Orleans Stream SubscriptionId 生成机制详解
java·系统架构·c#
向宇it1 天前
【unity实战】MapMagic 2实战例子
游戏·3d·unity·c#·游戏引擎
"菠萝"1 天前
C#知识学习-017(修饰符_6)
学习·c#
VB.Net1 天前
C#循序渐进
开发语言·c#
feifeigo1231 天前
C# WinForms实现模拟叫号系统
c#