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);

}

}

}

相关推荐
林川~0110 小时前
Unity 万能物理检测工具:射线检测 / 范围检测 / 层级过滤 / 编辑器可视化(可直接拿去用)
游戏·unity·c#·射线检测·通用工具
He BianGu14 小时前
【WPF-VisionMaster】机器视觉通用平台V5.0版本发行说明
opencv·c#·wpf·halcon·机器视觉·visionmaster
tang_042714 小时前
【Hi.Ltd 专题】第9期:Interop 配置互操作(JSON/INI/XML/YAML/注册表/扫码)
经验分享·c#·hi.ltd系列
tang_042720 小时前
【Hi.Ltd 专题】第7期:Threading 采集线程、锁与 LRU 缓存
经验分享·c#·hi.ltd系列
A_nanda20 小时前
C# 界面卡顿:从定位到根治
c#
2501_9307077821 小时前
使用C#代码为新创建的 Word 文档创建目录
c#·word
czhc11400756631 天前
同一个数,两把尺子:六组“看着一样、其实不一样“
c#
花北城1 天前
【C#底层库】access_token授权鉴权验证
c#·鉴权·token·授权
rick9771 天前
C# 动态代理与 DispatchProxy:从原理到实战的完整指南
c#
tang_04271 天前
【Hi.Ltd 专题】第8期:Managements 插件、单例与服务定位
经验分享·c#·hi.ltd系列