如何在.net中模拟post方式提交json数据
展开全部
/// <summary>
/// Post获取信息
/// </summary>
/// <typeparam name="T">实体对象</typeparam>
/// <param name="url">post url</param>
/// <param name="data">post data</param>
/// <returns></returns>
public static T PostOfUrl<T>(string url, string data)
{
System.Net.HttpWebRequest httpWebRequest = (HttpWebRequest)System.Net.WebRequest.Create(url);
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Accept-Charset", "utf-8");
byte[] postBytes = Encoding.UTF8.GetBytes(data);
//httpWebRequest.ContentType = "text/xml";
httpWebRequest.ContentType = "application/json; charset=utf-8";// httpWebRequest.ContentLength = Encoding.UTF8.GetByteCount(data);//strJson为json字符串
Stream stream = httpWebRequest.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();//发送完毕,接受返回值
var response = httpWebRequest.GetResponse();
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
String responseString = streamRead.ReadToEnd();
JavaScriptSerializer js = new JavaScriptSerializer();
var list = js.Deserialize<T>(responseString);
return list;
}
/// Post获取信息
/// </summary>
/// <typeparam name="T">实体对象</typeparam>
/// <param name="url">post url</param>
/// <param name="data">post data</param>
/// <returns></returns>
public static T PostOfUrl<T>(string url, string data)
{
System.Net.HttpWebRequest httpWebRequest = (HttpWebRequest)System.Net.WebRequest.Create(url);
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Accept-Charset", "utf-8");
byte[] postBytes = Encoding.UTF8.GetBytes(data);
//httpWebRequest.ContentType = "text/xml";
httpWebRequest.ContentType = "application/json; charset=utf-8";// httpWebRequest.ContentLength = Encoding.UTF8.GetByteCount(data);//strJson为json字符串
Stream stream = httpWebRequest.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();//发送完毕,接受返回值
var response = httpWebRequest.GetResponse();
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
String responseString = streamRead.ReadToEnd();
JavaScriptSerializer js = new JavaScriptSerializer();
var list = js.Deserialize<T>(responseString);
return list;
}
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询