如何在.net中模拟post方式提交json数据
2个回答
展开全部
c# 模拟post 提交
string postData = "user=123&pass=456"; // 要发放的数据
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest objWebRequest = (HttpWebRequest)WebRequest.Create("http://www.abc.com/a.aspx");
objWebRequest.Method = "POST";
objWebRequest.ContentType = "application/x-www-form-urlencoded";
objWebRequest.ContentLength = byteArray.Length;
Stream newStream = objWebRequest.GetRequestStream();
// Send the data.
newStream.Write(byteArray, 0, byteArray.Length); //写入参数
newStream.Close();
HttpWebResponse response = (HttpWebResponse)objWebRequest.GetResponse();
StreamReader sr=new StreamReader(response.GetResponseStream(), Encoding.Default);
string textResponse = sr.ReadToEnd(); // 返回的数据
string postData = "user=123&pass=456"; // 要发放的数据
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest objWebRequest = (HttpWebRequest)WebRequest.Create("http://www.abc.com/a.aspx");
objWebRequest.Method = "POST";
objWebRequest.ContentType = "application/x-www-form-urlencoded";
objWebRequest.ContentLength = byteArray.Length;
Stream newStream = objWebRequest.GetRequestStream();
// Send the data.
newStream.Write(byteArray, 0, byteArray.Length); //写入参数
newStream.Close();
HttpWebResponse response = (HttpWebResponse)objWebRequest.GetResponse();
StreamReader sr=new StreamReader(response.GetResponseStream(), Encoding.Default);
string textResponse = sr.ReadToEnd(); // 返回的数据
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
2016-03-07
展开全部
试试下面的代码
private string HttpPost(string Url, string postDataStr)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
Stream myRequestStream = request.GetRequestStream();
StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
myStreamWriter.Write(postDataStr);
myStreamWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |