HttpWebRequest 自定义header,Post发送请求,请求形式是json,坑爹的代码

Posted 厚德载物

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpWebRequest 自定义header,Post发送请求,请求形式是json,坑爹的代码相关的知识,希望对你有一定的参考价值。

public static string PostMoths(string url, LoginDTO obj_model, Dictionary<string, string> dic = null)
{
dic = new Dictionary<string, string>();
dic.Add("Abp.TenantId", "null");
// .AspNetCore.Culture:zh - CN
dic.Add(".AspNetCore.Culture", "zh-CN");
string param = JsonConvert.SerializeObject(obj_model);
System.Net.HttpWebRequest request;
request = (System.Net.HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json;charset=UTF-8";
if (dic != null && dic.Count != 0)
{
foreach (var item in dic)
{
request.Headers.Add(item.Key, item.Value);
}
}
byte[] payload;
payload = System.Text.Encoding.UTF8.GetBytes(param);
request.ContentLength = payload.Length;
string strValue = "";
try
{
Stream writer = request.GetRequestStream();
writer.Write(payload, 0, payload.Length);
writer.Close();
System.Net.HttpWebResponse response;
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.Stream s;
s = response.GetResponseStream();
string StrDate = "";
StreamReader Reader = new StreamReader(s, Encoding.UTF8);
while ((StrDate = Reader.ReadLine()) != null)
{
strValue += StrDate;
}
}
catch (Exception e)
{
strValue = e.Message;
}
return strValue;











































以上是关于HttpWebRequest 自定义header,Post发送请求,请求形式是json,坑爹的代码的主要内容,如果未能解决你的问题,请参考以下文章

继承 httpwebrequest和HttpWebResponse类时遇到错误 CS1729

阻止 HttpWebRequest 检查我的有效负载

Silverlight 不支持 HttpWebRequest 上的标头

将自签名证书与 .NET 的 HttpWebRequest/Response 一起使用

如何自定义UITableView的Header

python requests headers自定义问题