HttpClient.cs

出自 ProgWiki
前往: 導覽搜尋

System.Net.HttpWebRequest

用途

提供 WebRequest 類別的 HTTP 特定實作。

程式碼

  • 注意事項:如果遠端網站的語系,跟近端網站的語系不同時,有時需改寫 System.Text.Encoding.Default ,以避免抓回來的網頁變亂碼。
  • 例如:
  1. 簡體字的網頁改用 Encoding.GetEncoding("GB2312")
  2. 繁體字的網頁改用 Encoding.GetEncoding("BIG5")
using System;
using System.Web;
using System.IO;
using System.Net;
using System.Text;
using System.Collections.Generic;  
 
/// <summary>
/// HttpClient 的摘要描述
/// </summary>
public class HttpClient
{
	public static string Get(string strUrl)
	{
		return HttpClient.Get(strUrl, System.Text.Encoding.Default);
	}
 
	public static string Get(string strUrl, Encoding TextEncoding)
	{
		string strRet = "";
		Uri uri = new Uri(strUrl);
		HttpWebRequest hwReq = WebRequest.Create(uri) as HttpWebRequest;
		hwReq.Method = "GET";
		hwReq.KeepAlive = false;
		hwReq.Timeout = 10000;
 
		using (HttpWebResponse hwRes = hwReq.GetResponse() as HttpWebResponse)
		{
			using (StreamReader reader = new StreamReader(hwRes.GetResponseStream(), TextEncoding))
			{
				strRet = reader.ReadToEnd();
			}
		}
		return strRet;
	}
 
	public static string Post(string strUrl, Dictionary<string, string> postData)
	{
		return HttpClient.Post(strUrl, postData, System.Text.Encoding.Default);
	}
 
	public static string Post(string strUrl, Dictionary<string, string> postData, Encoding TextEncoding)
	{
		string strRet = "";
		Uri uri = new Uri(strUrl);
		HttpWebRequest hwReq = WebRequest.Create(uri) as HttpWebRequest;
 
		hwReq.Method = "POST";
		hwReq.KeepAlive = false;
		hwReq.Timeout = 10000;
		hwReq.ContentType = "application/x-www-form-urlencoded";
 
		StringBuilder data = new StringBuilder();
		string ampersand = "";
		foreach (string key in postData.Keys)
		{
			data.Append(ampersand).Append(key).Append("=").Append(HttpUtility.UrlEncode(postData[key]));
			ampersand = "&";
		}
 
		byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
 
		// 設定寫入內容長度
		hwReq.ContentLength = byteData.Length;
 
		// 寫入 POST 參數  
		using (Stream postStream = hwReq.GetRequestStream())
		{
			postStream.Write(byteData, 0, byteData.Length);
		}
 
		using (HttpWebResponse hwRes = hwReq.GetResponse() as HttpWebResponse)
		{
			using (StreamReader reader = new StreamReader(hwRes.GetResponseStream(), TextEncoding))
			{
				strRet = reader.ReadToEnd();
			}
		}
		return strRet;
	}
}

參照