public static string Post(string url, string postPar = null)
{
#region 构造一个“HttpWebRequest”
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
#endregion
if (postPar == null)
goto GetResponse;
#region 将参数转为字节组写入 “需求流”
byte[] postConByte = Encoding.Default.GetBytes(postPar);
httpWebRequest.ContentLength = postConByte.Length;
using (Stream stream = httpWebRequest.GetRequestStream())
stream.Write(postConByte, 0, postConByte.Length);
#endregion
GetResponse:
{
#region 从“响应流”里读取结果
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (Stream responseStream = httpWebResponse.GetResponseStream())
{
StreamReader streamReader = new StreamReader(responseStream);
string postResult = streamReader.ReadToEnd();
return postResult;
}
#endregion
}
}
需要引用的命名空间
using System.Net; using System.Text; using System.IO;
个人笔记 仅供参考 欢迎指正
|