ASP.Net 后台Post 请求
此方法不是本人原创,记载于此方便日后查看,以及有需要的童鞋参考
调用:
string strKey = "12345678";
string content = SecurityHelper.EncodeBase64(strKey);
string message = Utils.RequestorHelper.PostWebRequest("Url", "title=公告测试&content=" + content + "&verify=be10c510b5f4f082dbd4268820cde895", new UTF8Encoding());
public static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
{
string ret = string.Empty;
try
{
byte[] byteArray = dataEncode.GetBytes(paramData); //转化
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded";
webReq.ContentLength = byteArray.Length;
Stream newStream = webReq.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);//写入参数
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), dataEncode);
ret = sr.ReadToEnd();
sr.Close();
response.Close();
newStream.Close();
}
catch (Exception ex)
{
//Response.Write(ex.Message);
}
return ret;
}
另一种方式:
public static string SendHttpPost( string url, NameValueCollection data)
{
System.Net.WebClient wc = new System.Net.WebClient();
wc.Headers.Add("Accept-Language", "zh-cn");
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
byte[] bytReturn = wc.UploadValues(url, "post", data);
wc.Dispose();
return System.Text.Encoding.GetEncoding("gbk").GetString(bytReturn);
}