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";
            }
        }
    }
}
相关推荐
Humbunklung4 小时前
C# 使用应用RSA和ECC进行数字签名和签名验证
开发语言·c#·rsa·ecc
Rotion_深4 小时前
C# WPF使用线程池运行Action方法
c#·wpf·线程池
大飞pkz6 小时前
【设计模式】策略模式
开发语言·设计模式·c#·策略模式
cgsthtm6 小时前
C#使用linq将数据进行分页
c#·linq·分页·sqlsugar
玩泥巴的6 小时前
不一样的.NET烟火,基于Roslyn的开源代码生成器
c#·.net·代码生成·roslyn
"菠萝"6 小时前
C#知识学习-015(修饰符_4)
开发语言·windows·c#
asdzx677 小时前
使用C#将Markdown转换为Word或PDF:高效文档转换的利器
经验分享·c#
sali-tec7 小时前
C# 基于halcon的视觉工作流-章39-OCR识别
开发语言·图像处理·算法·计算机视觉·c#·ocr
mudtools7 小时前
.net操作Excel:图表 (Chart) 的创建与定制
c#·.net·excel·wps
ajassi20009 小时前
开源 C# 快速开发(八)通讯--Tcp服务器端
开发语言·开源·c#