.NET Framework提供類處理HTTP請求。這篇文章講述一下處理GET和POST請求。
概述
簡單GET請求
簡單POST請求
HTTP授權請求
錯誤處理
深入閱讀
概述
System.Net命名空間包含 HttpWebRequest和
HttpWebResponse
類,這兩個類可以從web服務器獲取數據和使用基於HTTP的服務。通常你需要添加System.Web的引用,這樣就可以使用
HttpUtility
類,這個類可以提供方法對 HTML
和URL的文本進行編碼或者解碼。
雅虎web服務返回XML數據。有些web服務返回其他格式的數據,比如JSON和序列化的PHP,.NET
Framework自從擴展支持處理xml數據之後,處理這種格式的數據就特別簡單了。
簡單GET請求
接下來的例子獲取網頁並打印出源碼。
C# GET 例1
using System;
using System.IO;
using System.Net;
using System.Text;
// Create the web request
HttpWebRequest request = WebRequest.Create("https://developer.yahoo.com/") as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Console.WriteLine(reader.ReadToEnd());
}
簡單POST請求
C# POST例1
// We use the HttpUtility class from the System.Web namespace
using System.Web;
Uri address = new Uri("http://api.search.yahoo.com/ContentAnalysisService/V1/termExtraction");
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Create the data we want to send
string appId = "YahooDemo";
string context = "Italian sculptors and painters of the renaissance"
+ "favored the Virgin Mary for inspiration";
string query = "madonna";
StringBuilder data = new StringBuilder();
data.Append("appid=" + HttpUtility.UrlEncode(appId));
data.Append("&context=" + HttpUtility.UrlEncode(context));
data.Append("&query=" + HttpUtility.UrlEncode(query));
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Console.WriteLine(reader.ReadToEnd());
}
C# HTTP AUTHENTICATION
// Create the web request
HttpWebRequest request
= WebRequest.Create("https://api.del.icio.us/v1/posts/recent") as HttpWebRequest;
// Add authentication to request
request.Credentials = new NetworkCredential("username", "password");
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Console.WriteLine(reader.ReadToEnd());
}
錯誤處理
HttpRequest.GetResponse()
方法在服務器沒有返回狀態碼200(表示OK),請求超時和網絡錯誤的時候,會引發錯誤。但是,重定向會自動處理的。C# GET 例2
public static void PrintSource(Uri address)
{
HttpWebRequest request;
HttpWebResponse response = null;
StreamReader reader;
StringBuilder sbSource;
if (address == null) { throw new ArgumentNullException("address"); }
try
{
// Create and initialize the web request
request = WebRequest.Create(address) as HttpWebRequest;
request.UserAgent = ".NET Sample";
request.KeepAlive = false;
// Set timeout to 15 seconds
request.Timeout = 15 * 1000;
// Get response
response = request.GetResponse() as HttpWebResponse;
if (request.HaveResponse == true && response != null)
{
// Get the response stream
reader = new StreamReader(response.GetResponseStream());
// Read it into a StringBuilder
sbSource = new StringBuilder(reader.ReadToEnd());
// Console application output
Console.WriteLine(sbSource.ToString());
}
}
catch (WebException wex)
{
// This exception will be raised if the server didn't return 200 - OK
// Try to retrieve more information about the network error
if (wex.Response != null)
{
using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)
{
Console.WriteLine(
"The server returned '{0}' with the status code {1} ({2:d}).",
errorResponse.StatusDescription, errorResponse.StatusCode,
errorResponse.StatusCode);
}
}
}
finally
{
if (response != null) { response.Close(); }
}
}
深入閱讀