public static string PostJson(string url, string jsonParam,string encode)
{
string strURL = url;
System.Net.HttpWebRequest request;
request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
request.Method = "POST";
request.ContentType = "application/json;charset="+encode.ToUpper();
string paraUrlCoded = jsonParam;
byte[] payload;
payload = System.Text.Encoding.GetEncoding(encode.ToUpper()).GetBytes(paraUrlCoded);
request.ContentLength = payload.Length;
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 = "";
string strValue = "";
StreamReader Reader = new StreamReader(s, Encoding.GetEncoding(encode.ToUpper()));
while ((StrDate = Reader.ReadLine()) != null)
{
strValue += StrDate + "\r\n";
}
return strValue;
}
{
string strURL = url;
System.Net.HttpWebRequest request;
request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
request.Method = "POST";
request.ContentType = "application/json;charset="+encode.ToUpper();
string paraUrlCoded = jsonParam;
byte[] payload;
payload = System.Text.Encoding.GetEncoding(encode.ToUpper()).GetBytes(paraUrlCoded);
request.ContentLength = payload.Length;
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 = "";
string strValue = "";
StreamReader Reader = new StreamReader(s, Encoding.GetEncoding(encode.ToUpper()));
while ((StrDate = Reader.ReadLine()) != null)
{
strValue += StrDate + "\r\n";
}
return strValue;
}
本文介绍了一个使用C#实现的向指定URL发送POST请求并附带JSON参数的方法。该方法支持自定义编码方式,通过设置请求头为application/json来确保JSON数据能够正确传递。
295

被折叠的 条评论
为什么被折叠?



