C# 用POST提交json数据
public void GetResponse(string url, string json)
{
Encoding encoding = Encoding.UTF8;
byte[] data = encoding.GetBytes(json);
//此处为为http请求url
var uri = new Uri(url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
//用此方法可以添加标准或非标准http请求,诸如conten-type ,accept,range等
request.Headers.Add("X-Auth-Token", System.Web.HttpUtility.UrlEncode("openstack"));
//此处为C#实现的一些标准http请求头添加方法,用上面的方面也可以实现
request.ContentType = "application/json";
request.Accept = "application/json";
// request.ContentLength = data.Length;
//此处添加标准http请求方面
request.Method = "POST";
System.IO.Stream sm = request.GetRequestStream();
sm.Write(data, 0, data.Length);
sm.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8);
Char[] readBuff = new Char[256];
int count = streamRead.Read(readBuff, 0, 256);
//content为http响应所返回的字符流
String content = "";
while (count > 0)
{
String outputData = new String(readBuff, 0, count);
content += outputData;
count = streamRead.Read(readBuff, 0, 256);
}
response.Close();
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。