webpost

public static string GetContentPost(string uri, string contentType, string data, Encoding coding,string appname, int timeout = 10000)

{

coding = coding ?? Encoding.UTF8;

byte\[\] buffer = !string.IsNullOrEmpty(data) ? coding.GetBytes(data) : new byte0;

WebRequest request = WebRequest.Create(uri);

request.Method = "POST";

request.ContentType = contentType;

request.ContentLength = buffer.Length;

request.Proxy = null;

//request.Headers.Add("Authorization", Authorization); //添加Authorization头

request.Timeout = timeout;

request.Headers.Add("appname", appname);

using (Stream stream = request.GetRequestStream())

{

stream.Write(buffer, 0, buffer.Length);

}

try

{

using (WebResponse response = request.GetResponse())

using (Stream stream = response.GetResponseStream())

{

return new StreamReader(stream, coding).ReadToEnd();

}

}

catch (WebException ex) when (ex.Response != null)

{

using (var response = ex.Response)

using (var stream = response.GetResponseStream())

{

string errorContent = new StreamReader(stream, coding).ReadToEnd();

//获取HTTP状态码

HttpStatusCode statusCode = ((HttpWebResponse)response).StatusCode;

//写入EX的massage

throw new WebException($"请求失败: {ex.Status}" +

$"\r\n HTTP状态码:{statusCode} " +

$"\r\n URL:{uri} ", ex);

}

}

}

相关推荐
WarPigs1 天前
C# dll笔记
c#
淡笑沐白1 天前
C# HttpClient完整使用指南
c#·httpclient
JaydenAI1 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
小满Autumn1 天前
MVVM Light 架构笔记:定位器、命令、消息与 IoC 实践
笔记·学习·架构·c#·上位机·mvvm
小满Autumn1 天前
CommunityToolkit.Mvvm 架构笔记:现代 MVVM、源生成器与工程化实践
笔记·架构·c#·.net·wpf·mvvm
加号31 天前
【C#】 JSON 序列化与反序列化:从入门到最佳实践
c#·json
胖纸不争1 天前
自建 Copilot Cli 代理:让 GitHub Copilot 真正"Bring Your Own Key"
ai·c#
FuckPatience2 天前
C# new List<T>(IEnumerable<T> collection),链表初始化时传入已存在链表
链表·c#·list
专注VB编程开发20年2 天前
工控上位机开发为什么固死.net 4.5.2sdk?适配win7
python·信息可视化·c#
狂人开飞机2 天前
18. 中介者模式(Mediator Pattern)
设计模式·c#·中介者模式