InternetClient.cs

出自 ProgWiki
前往: 導覽搜尋

用途

  • HTTP的Get與Post。
  • FTP的DownloadFile。

程式碼

  • 注意事項:如果遠端網站的語系,跟近端網站的語系不同時,有時需改寫 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>
/// InternetClient 的摘要描述
/// </summary>
public class InternetClient
{
	public static string UserID = string.Empty;     //連線驗證用的帳號
	public static string Password = string.Empty;   //連線驗證用的密碼
	public static bool KeepAlive = false;   //是否保持連線
	public static int Timeout = 10000;      //預設TimeOut=10秒
 
#region Http
	public static string HttpGet(string strUrl)
	{
		return InternetClient.HttpGet(strUrl, System.Text.Encoding.Default);
	}
 
	public static string HttpGet(string strUrl, Encoding TextEncoding)
	{
		string strRet = "";
		Uri uri = new Uri(strUrl);
		HttpWebRequest hwReq = WebRequest.Create(uri) as HttpWebRequest;
 
        	if ((string.IsNullOrEmpty(UserID) == false) && (string.IsNullOrEmpty(Password) == false))
			hwReq.Credentials = new NetworkCredential(UserID, Password);
 
	        hwReq.Method = WebRequestMethods.Http.Get;
        	hwReq.KeepAlive = KeepAlive;
	        hwReq.Timeout = Timeout;
 
		using (HttpWebResponse hwRes = hwReq.GetResponse() as HttpWebResponse)
		{
			using (StreamReader reader = new StreamReader(hwRes.GetResponseStream(), TextEncoding))
			{
				strRet = reader.ReadToEnd();
			}
		}
		return strRet;
	}
 
	public static string HttpPost(string strUrl, Dictionary<string, string> postData)
	{
		return InternetClient.HttpPost(strUrl, postData, System.Text.Encoding.Default);
	}
 
	public static string HttpPost(string strUrl, Dictionary<string, string> postData, Encoding TextEncoding)
	{
		string strRet = "";
		Uri uri = new Uri(strUrl);
		HttpWebRequest hwReq = WebRequest.Create(uri) as HttpWebRequest;
 
        	if ((string.IsNullOrEmpty(UserID) == false) && (string.IsNullOrEmpty(Password) == false))
			hwReq.Credentials = new NetworkCredential(UserID, Password);
 
		hwReq.Method = WebRequestMethods.Http.Post;
		hwReq.KeepAlive = KeepAlive;
		hwReq.Timeout = Timeout;
		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;
    }
#endregion Http
 
#region Ftp
    public static string FtpDownload(string strUrl)
    {
        return InternetClient.FtpDownload(strUrl, System.Text.Encoding.Default);
    }
 
    public static string FtpDownload(string strUrl, Encoding TextEncoding)
    {
        string strRet = "";
        Uri uri = new Uri(strUrl);
        FtpWebRequest fwReq = WebRequest.Create(uri) as FtpWebRequest;
 
        if ((string.IsNullOrEmpty(UserID) == false) && (string.IsNullOrEmpty(Password) == false))
            fwReq.Credentials = new NetworkCredential(UserID, Password);
 
        fwReq.Method = WebRequestMethods.Ftp.DownloadFile;
        fwReq.KeepAlive = KeepAlive;
        fwReq.Timeout = Timeout;
 
        using (FtpWebResponse fwRes = fwReq.GetResponse() as FtpWebResponse)
        {
            using (StreamReader reader = new StreamReader(fwRes.GetResponseStream(), TextEncoding))
            {
                strRet = reader.ReadToEnd();
            }
        }
        return strRet;
    }
 
#endregion Ftp
 
}