C#获取POST请求发来的数据
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#获取POST请求发来的数据相关的知识,希望对你有一定的参考价值。
这是POST请求发来的数据,应该怎么解析呢?
参考技术A使用POST请求获取结果
2.1 创建LoginHandler.aspx处理页面
[csharp] view plain copy
protected void Page_Load(object sender, EventArgs e)
string result = "";
string userName = Request.Form["UserName"];
string password = Request.Form["Password"];
if (userName == "admin" && password == "123")
result = "登陆成功";
else
result = "登陆失败";
Response.Write(result);
2.2 编写POST请求与获取结果方法
[csharp] view plain copy
/// <summary>
/// POST请求与获取结果
/// </summary>
public static string HttpPost(string Url, string postDataStr)
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postDataStr.Length;
StreamWriter writer = new StreamWriter(request.GetRequestStream(),Encoding.ASCII);
writer.Write(postDataStr);
writer.Flush();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
encoding = "UTF-8"; //默认编码
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
string retString = reader.ReadToEnd();
return retString;
2.3 调用测试
[csharp] view plain copy
static void Main(string[] args)
string url = "http://www.mystudy.cn/LoginHandler.aspx";
string data = "UserName=admin&Password=123";
string result = HttpPost(url, data);
Console.WriteLine(result);
Console.ReadLine();
求一个c#的 post请求 json 并且接收返回json数据的一个demo。
参考技术A public string HttpPost(string url,string data)HttpWebRequest request=(HttpWebRequest)WebRequest.Create(url);
request.ContentType="application/json";
request.Method="POST";
byte[] buffer=Encoding.UTF8.GetBytes(data);
using(Stream stream=request.GetRequestStream())
stream.Write(buffer,0,buffer.Length);
HttpWebResponse response=(HttpWebResponse)request.GetResponse();
string result=string.Empty;
using(StreamReader reader=new StreamReader(response.GetResponseStream()))
result=reader.ReadToEnd();
return result;
本回答被提问者采纳
以上是关于C#获取POST请求发来的数据的主要内容,如果未能解决你的问题,请参考以下文章
求一个c#的 post请求 json 并且接收返回json数据的一个demo。