補充說明:
現在項目已經遷移到 GitHub, 地址:https://github.com/j6mes/httplib/
今日,在 Codeplex 上看到一個開源項目,對 Http 協議進行了封裝,這下可以方便這些在 .NET 平台下訪問 Web 服務器的同學們了,比如,從 Web 服務器抓取一個頁面,使用 .NET 而不是借助瀏覽器向服務器發一個 Post 請求之類的操作,就可以直接調用一下實現好的方法了。
項目的地址:http://httplib.codeplex.com/
也可以直接到下載頁面下載你需要的源代碼或者編譯完成的類庫。
下載頁面的地址:http://httplib.codeplex.com/releases/view/99620
項目比較新,所以下載量看來並不大。
項目的使用說明:
在項目的首頁上有一個簡短的說明,雖然簡單,但是比較使用。
Project 說明
HttpLib 使得在 C# 中異步地訪問 Web 服務器上的數據變得更加容易。 庫中包含了將文件上傳到服務器中以及從服務器下載頁面的方法。
這個項目設計用來訪問當前已經存在的 Web 服務。如果你計划創建新的包含服務器端和客戶端的應用,建議考慮使用 WCF.
支持的 HTTP 方法
- GET
- POST
- Form Encoded
- Multipart File Upload
- PUT
- HEAD
- DELETE
示例
首先,在項目中引用 httplib 程序集。
在代碼的開頭部門,一般先 using 命名空間。
using Redslide.HttpLib
從服務器端獲取內容。比如抓取頁面。
Request.Get("http://google.com/", result=> { Console.Write(result); });
向服務器提交信息,使用 Post 方式。提交的參數使用一個對象表示。
Request.Post("http://testing.local/post.php", new {name="james",username="Redslide"}, result=> { Console.Write(result); });
以 Post 方式提交信息,如果出現異常,捕獲異常。
Request.Post("http://testing.local/post.php", new { name = "value"}, result=> { Console.Write(result); }, e=> { Console.Write(e.ToString()); });
上傳文件到服務器,第三個參數是上傳文件。
Request.Upload("http://testing.local/post.php", new {name = "value"}, new[] { new NamedFileStream("file", "photo.jpg", "image/jpeg", new FileStream(@"C:\photo.jpg",FileMode.Open)) }, result=> { Console.Write(result); });