.Net C#的網頁瀏覽器

今天利用了一點時間寫了 C# 的網頁瀏覽器。

public class WebClient {
public static void Main() {

CookieContainer cookieContainer = new CookieContainer();
// 可登入網站運作。
string s = requestWithPost("http://localhost/test/intranet/init.do", "POST", null, cookieContainer);
Console.WriteLine(s.IndexOf("") );
s = requestWithPost("http://localhost/test/j_spring_security_check", "POST", new Dictionary() { { "j_username", "username" }, { "j_password", "password" } }, cookieContainer);
Console.WriteLine(s.IndexOf(""));
s = requestWithPost("http://localhost/test/intranet/init.do", "POST", null, cookieContainer);
Console.WriteLine(s.IndexOf(""));

// 取得byte後 存檔。
ToFile("C:/Temp/google.gif", requestBytesWithPost("https://www.google.com.tw/intl/zh-TW_ALL/images/logos/images_logo_lg.gif", "GET", null, cookieContainer));

Console.ReadLine();
}

public static byte[] requestBytesWithPost(string reuestUri, string method, Dictionary datas, CookieContainer cookieContainer) {
string urlData = "";
string responseUri = "";
if (!string.IsNullOrEmpty(reuestUri)) {
if (datas != null && datas.Count > 0) {
foreach (KeyValuePair dataItem in datas) {
urlData += "&" + System.Web.HttpUtility.UrlEncode(dataItem.Key, Encoding.UTF8) + "=" + System.Web.HttpUtility.UrlEncode(dataItem.Value, Encoding.UTF8);
}
urlData = urlData.Substring(1);
}

string[] urlSplits = reuestUri.Split('/');
byte[] bytes = doRequestWithBytesPostData(reuestUri, method, Encoding.UTF8.GetBytes(urlData), cookieContainer,
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)",
" image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*",
urlSplits[0] + "/" + urlSplits[1] + "/" + urlSplits[2],
"application/x-www-form-urlencoded; charset = UTF-8", out responseUri);
// Console.WriteLine(responseUri);
return bytes;
}
return null;
}

public static string requestWithPost(string reuestUri, string method, Dictionary datas, CookieContainer cookieContainer) {
if (!string.IsNullOrEmpty(reuestUri)) {
return System.Text.Encoding.UTF8.GetString( requestBytesWithPost(reuestUri, method, datas, cookieContainer) );
}
return null;
}

public static byte[] doRequestWithBytesPostData(string requestUri, string method, byte[] postData,
CookieContainer cookieContainer,
string userAgent, string acceptHeaderString,
string referer,
string contentType, out string responseUri) {
if (!string.IsNullOrEmpty(requestUri)) {
// // // var request = WebRequest.Create(requestUri) as HttpWebRequest;
HttpWebRequest request = null;

if (requestUri.StartsWith("https", StringComparison.OrdinalIgnoreCase)) {
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(requestUri) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
} else {
request = WebRequest.Create(requestUri) as HttpWebRequest;
}

if (request != null) {
request.KeepAlive = true;
request.AllowAutoRedirect = true;
request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache);
request.Expect = null;
if (!string.IsNullOrEmpty(method))
request.Method = method;
if (!string.IsNullOrEmpty(acceptHeaderString))
request.Accept = acceptHeaderString;
if (!string.IsNullOrEmpty(referer))
request.Referer = referer;
if (!string.IsNullOrEmpty(contentType))
request.ContentType = contentType;
if (!string.IsNullOrEmpty(userAgent))
request.UserAgent = userAgent;
if (cookieContainer != null)
request.CookieContainer = cookieContainer;

request.Timeout = 1000; // Constants.RequestTimeOut;

if (request.Method == "POST") {
if (postData != null) {
request.ContentLength = postData.Length;
using (var dataStream = request.GetRequestStream()) {
dataStream.Write(postData, 0, postData.Length);
}
}
}
try {
MemoryStream memoryStream = new MemoryStream(0x10000);
using (var httpWebResponse = request.GetResponse() as HttpWebResponse) {
if (httpWebResponse != null) {
responseUri = httpWebResponse.ResponseUri.AbsoluteUri;
cookieContainer.Add(httpWebResponse.Cookies);
using (Stream responseStream = request.GetResponse().GetResponseStream()) {
byte[] buffer = new byte[0x1000];
int countBuffer;
while ((countBuffer = responseStream.Read(buffer, 0, buffer.Length)) > 0) {
memoryStream.Write(buffer, 0, countBuffer);
}
}
return memoryStream.ToArray();
// // // return System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
}
}
} catch (Exception e) {
Console.WriteLine("Exception caught in process: {0}", e.ToString());
}
}
}
responseUri = null;
return null;
}
private static bool CheckValidationResult(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, SslPolicyErrors errors) {
return true;
}
public static bool ToFile(string fileName, byte[] bytes) {
try {
System.IO.FileStream fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
fileStream.Write(bytes, 0, bytes.Length);
fileStream.Close();
return true;
} catch (Exception e) {
Console.WriteLine("Exception caught in process: {0}", e.ToString());
}
return false;
}

}

廣告

About fenjj

Perfect !!??...
本篇發表於 Uncategorized。將永久鏈結加入書籤。

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s