using System; using System.Collections.Generic; using System.Net; //使用 httpwebresponse 等類庫 using System.IO; // 序列化 using System.Text; //文本 namespace M ...
using System; using System.Collections.Generic; using System.Net; //使用 httpwebresponse 等類庫 using System.IO; // 序列化 using System.Text; //文本 namespace MyTestHttpWebRequest { public class Test { /// <summary> /// 消息提交 /// </summary> /// <param name="str">需要提交的內容</param> /// <param name="url">地址</param> /// <returns></returns> public string TestHttpWebRequest(string str, string url) { HttpWebRequest httpwebrequest = WebRequest.Create(url) as HttpWebRequest; //定義 //--填寫標頭--// httpwebrequest.ContentType = "application/x-www-form-urlencoded";//提交格式-from格式 httpwebrequest.Accept = "*/*"; httpwebrequest.UserAgent = "Mozilla-Firefox-Spider(Kolee)"; //服務代理 //--提交方式--// httpwebrequest.Method = " POST"; //--獲取信息--// Stream stream = httpwebrequest.GetResponse().GetResponseStream();//獲取流 //------------------寫入------------------// StreamWriter streamwriter = new StreamWriter(stream);//放入寫入流 streamwriter.Write(str);//寫入流 streamwriter.Flush();//推入流 //------------------讀取-------------------// StreamReader streamreader = new StreamReader(stream);//放入讀取流 string resout = streamreader.ReadToEnd(); //讀取流結果 streamwriter.Close(); streamreader.Close(); return resout; //返回從網頁讀取的返回值 } } //這裡是 提交的頁面讀取部分 public partial class _Default : System.Web.UI.Page//繼承page頁面 { protected void Page_Load(object sender, EventArgs e) { if (Request.HttpMethod == "POST")//選定提交方式 { Stream stream = Request.InputStream;//獲取流 StreamReader str = new StreamReader(stream, System.Text.Encoding.UTF8);//放入讀取流 Response.Write(str.ReadToEnd().ToString() + "<這裡是接收的部分>");//輸出得到的結果 str.Close();//關閉流 Response.Write("接收成功"); } } } }
//需要註意的是:url如果有POST提交的話。必須精確到頁面
——————————————————————————————如果無法使用,可以嘗試使用位元組的方法———————————————————————
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; namespace RestApiSdk { public class HttpPost { public string SendAll(string Url, string jsonString) { #region 發送HTTP POST 數據 HttpWebRequest httpWebRequest = WebRequest.Create(Url) as HttpWebRequest; httpWebRequest.Method = "POST"; httpWebRequest.ContentType = "application/json"; byte[] data = System.Text.Encoding.UTF8.GetBytes(jsonString); using (Stream stream = httpWebRequest.GetRequestStream()) { stream.Write(data, 0, data.Length); } Stream responseStream = httpWebRequest.GetResponse().GetResponseStream(); string result = string.Empty; using (StreamReader responseReader = new StreamReader(responseStream, Encoding.UTF8)) { result = responseReader.ReadToEnd(); } return result; #endregion } } }