寫在前面
最近一直在研究sharepoint的文檔庫,在上傳文件到文檔庫的過程中,需要模擬post請求,也查找了幾種模擬方式,webclient算是比較簡單的方式。
一個例子
這里寫一個簡單接受post請求的aspx頁面,代碼如下:
1 namespace Wolfy.UploadDemo 2 { 3 public partial class Default : System.Web.UI.Page 4 { 5 protected void Page_Load(object sender, EventArgs e) 6 { 7 string fileName = Request.QueryString["url"]; 8 if (!string.IsNullOrEmpty(fileName)) 9 { 10 Stream st = Request.InputStream; 11 string fileSavePath = Request.MapPath("~/upload/") + fileName; 12 byte[] buffer=new byte[st.Length]; 13 st.Read(buffer, 0, buffer.Length); 14 if (!File.Exists(fileSavePath)) 15 { 16 File.WriteAllBytes(fileSavePath, buffer); 17 } 18 19 } 20 } 21 } 22 }
這里使用QueryString接收url參數,使用請求的輸入流接受文件的數據。
然后,使用webclient寫一個模擬請求的客戶端,代碼如下:
1 namespace Wolfy.UploadExe 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 WebClient client = new WebClient(); 8 client.QueryString.Add("url", "1.png");10 using (FileStream fs = new FileStream("1.png", FileMode.Open)) 11 { 12 byte[] buffer = new byte[fs.Length]; 13 fs.Read(buffer, 0, buffer.Length); 14 client.UploadData("http://localhost:15887/Default.aspx", buffer); 15 } 16 17 } 18 } 19 }
調試狀態運行aspx,然后運行exe控制台程序
如果有驗證信息,可以加上這樣一句話:
1 client.Credentials = new NetworkCredential("用戶名", "密碼", "域");
總結
由於目前做的項目,移動端app不能提供用戶名和密碼,必須使用證書進行認證,發現webclient無法支持。就采用HttpWebRequest類進行模擬了。關於它的使用是下文了。