http post 请求 ,参数使用 json 格式
using System.Net;
using System.IO;
public static string PostUrl(string url, string postData)
{
string result = "";
byte[] data = Encoding.UTF8.GetBytes(postData);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.Timeout = 800;
req.ContentType = "application/json";
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}
用法:
string result = PostUrl("http://127.0.0.1:3000/aesEncrypt", "{\"key\":\"lysm\",\"data\":\"123456\"}");
MessageBox.Show("服务器返回:" + result);
效果:
与 postman 结果相同
补充:带 cookie 的 http post 请求(配合服务端 session 使用)
public static string PostUrl(string url, string postData)
{
string result = "";
byte[] data = Encoding.UTF8.GetBytes(postData);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.Timeout = 800;
req.ContentType = "application/json";
req.ContentLength = data.Length;
req.CookieContainer = myCookieContainer;
try
{
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
resp.Cookies = myCookieContainer.GetCookies(req.RequestUri);
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
}
catch
{
result = "connect sever failed";
}
return result;
}