<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>No Meaning Developer &#187; library</title>
	<atom:link href="http://kentreez.com/blog/tag/library/feed/" rel="self" type="application/rss+xml" />
	<link>http://kentreez.com/blog</link>
	<description>kentreez&#039;s blog</description>
	<lastBuildDate>Sat, 31 Mar 2012 18:04:25 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>C# HttpRequester Class (HTTP Request Upload File with POST DATA )</title>
		<link>http://kentreez.com/blog/csharp/c-httprequester-class-upload-file-with-post-data/</link>
		<comments>http://kentreez.com/blog/csharp/c-httprequester-class-upload-file-with-post-data/#comments</comments>
		<pubDate>Wed, 19 Nov 2008 03:47:46 +0000</pubDate>
		<dc:creator>kentreez</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[HttpRequester]]></category>
		<category><![CDATA[library]]></category>

		<guid isPermaLink="false">http://journal.kentreez.com/?p=85</guid>
		<description><![CDATA[คือผมพยายามลอง Search หา Class ลักษณะนี้แล้วครับ แต่ก็หาไม่ได้สักที เจอแต่อัพโหลดไฟล์ได้อย่างเดียว หรือไม่ก็ POST DATA ได้อย่างเดียว สุดท้ายเลยต้องพยายามเขียนคลาสนี้ขึ้นมาใช้เองครับ จริงๆ เขียนไว้นานแล้วครับ แต่ไม่แน่ใจว่ามัน bug ตรงไหนรึป่าว เลยเก็บไว้ใช้เองสักพักนึงก่อน ตอนนี้คิดว่าใช้ได้โอเคแล้วครับ จึงนำมาแบ่งปัน อยากทำอะไรได้มากกว่านี้ ก็นำไปพัฒนาต่อได้เลยนะครับ ถ้าไงส่งตัวพัฒนามาให้ผมก็ดีนะครับ ผมจะได้ใช้ด้วย]]></description>
			<content:encoded><![CDATA[<p>คือผมพยายามลอง Search หา Class ลักษณะนี้แล้วครับ แต่ก็หาไม่ได้สักที เจอแต่อัพโหลดไฟล์ได้อย่างเดียว หรือไม่ก็ POST DATA ได้อย่างเดียว สุดท้ายเลยต้องพยายามเขียนคลาสนี้ขึ้นมาใช้เองครับ</p>
<p>จริงๆ เขียนไว้นานแล้วครับ แต่ไม่แน่ใจว่ามัน bug ตรงไหนรึป่าว เลยเก็บไว้ใช้เองสักพักนึงก่อน ตอนนี้คิดว่าใช้ได้โอเคแล้วครับ จึงนำมาแบ่งปัน</p>
<p>อยากทำอะไรได้มากกว่านี้ ก็นำไปพัฒนาต่อได้เลยนะครับ ถ้าไงส่งตัวพัฒนามาให้ผมก็ดีนะครับ ผมจะได้ใช้ด้วย <img src='http://kentreez.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p><span id="more-85"></span></p>
<pre class="brush: csharp; title: ; notranslate">
/*
___________________________________________________________________
Name:  HttpRequester Class
Version: 1
Date:  10/06/2008
Author:  Kentreez Jumrus
Description: Make HttpWebRequest with simple command.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Web;
using System.IO;
using System.Collections;

namespace Kentreez
{
	class HttpRequester
	{
		private HttpWebRequest httpWebRequest;
		private Stream requestStream;
		private Stream responseStream;
		private StreamReader responseReader;

		private ArrayList files;
		private ArrayList datas;
		private string sessionKey;
		private string sessionValue;
		private string sessionPath;
		private string sessionDomain;
		private string boundary;
		private string headerFileTemplate;
		private string headerPostDataTemplate;

		private string requestUrl;
		private string encoding;
		private string method;

		public HttpRequester()
		{
			this.files = new ArrayList();
			this.datas = new ArrayList();
			this.encoding = &quot;utf8&quot;;
			this.method = &quot;GET&quot;;
			this.headerPostDataTemplate = &quot;Content-Disposition: form-data; name=\&quot;{0}\&quot;\r\n\r\n{1}&quot;;
			this.headerFileTemplate = &quot;Content-Disposition: form-data; name=\&quot;{0}\&quot;;filename=\&quot;{1}\&quot;;\r\n Content-Type: application/octet-stream\r\n\r\n&quot;;
		}

		public void SetRequestUrl(string url)
		{
			this.requestUrl = url;
		}

		public void SetCharset(string encoding)
		{
			if (encoding.ToLower().Replace(&quot;-&quot;, &quot;&quot;).Equals(&quot;utf7&quot;))
			this.encoding = &quot;utf7&quot;;
			else if (encoding.ToLower().Replace(&quot;-&quot;, &quot;&quot;).Equals(&quot;utf8&quot;))
			this.encoding = &quot;utf8&quot;;
			else if (encoding.ToLower().Replace(&quot;-&quot;, &quot;&quot;).Equals(&quot;utf32&quot;))
			this.encoding = &quot;utf32&quot;;
			else if (encoding.ToLower().Replace(&quot;-&quot;, &quot;&quot;).Equals(&quot;unicode&quot;))
			this.encoding = &quot;unicode&quot;;
			else if (encoding.ToLower().Replace(&quot;-&quot;, &quot;&quot;).Equals(&quot;bigendianunicode&quot;))
			this.encoding = &quot;bigendianunicode&quot;;
			else if (encoding.ToLower().Replace(&quot;-&quot;, &quot;&quot;).Equals(&quot;ascii&quot;))
			this.encoding = &quot;ascii&quot;;
		}

		public void SetSession(string key, string value, string path, string domain)
		{
			this.sessionKey = key;
			this.sessionValue = value;
			this.sessionPath = path;
			this.sessionDomain = domain;
		}

		public void SetMethod(string method)
		{
			if (method.ToUpper().Equals(&quot;POST&quot;))
				this.method = &quot;POST&quot;;
			else
				this.method = &quot;GET&quot;;
		}

		public void AddFile(string name, string fileFullPath)
		{
			this.files.Add(new string[] { name, fileFullPath });
		}

		public void AddData(string name, string value)
		{
			this.datas.Add(new string[] { name, value });
		}

		public string Submit()
		{
			if (this.files.Count &gt; 0 || this.method.Equals(&quot;POST&quot;))
				return this.SubmitMethodPost();
			else
				return this.SubmitMethodGet();
		}

		private string SubmitMethodPost()
		{
			byte[] boundarybytes;

			// Create a boundry
			this.boundary = &quot;----------------------------&quot; + DateTime.Now.Ticks.ToString(&quot;x&quot;);

			// Create the web request
			this.httpWebRequest = (HttpWebRequest)WebRequest.Create(this.requestUrl);
			this.httpWebRequest.ContentType = &quot;multipart/form-data; boundary=&quot; + this.boundary;
			this.httpWebRequest.Method = &quot;POST&quot;;
			this.httpWebRequest.KeepAlive = true;
			this.httpWebRequest.AllowWriteStreamBuffering = true;
			this.httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;

			// Cookies
			this.httpWebRequest.CookieContainer = new CookieContainer();
			if (this.sessionKey != null &amp;&amp; this.sessionKey.Length &gt; 0 &amp;&amp; this.sessionValue != null &amp;&amp; this.sessionValue.Length &gt; 0)
			{
				this.httpWebRequest.CookieContainer.Add(new Cookie(this.sessionKey, this.sessionValue, this.sessionPath, this.sessionDomain));
			}

			this.httpWebRequest.ContentLength = 0;
			this.httpWebRequest.ContentLength += this.GetPostDataPacketLength();
			this.httpWebRequest.ContentLength += this.GetFilePacketLength();
			this.httpWebRequest.ContentLength += this.GetTrailingBoundary().Length;

			this.requestStream = this.httpWebRequest.GetRequestStream();

			// Write Post Data Packet
			this.StreamWritePostDataPacket();

			// Write files packet
			this.StreamWriteFilePacket();

			boundarybytes = Encoding.ASCII.GetBytes(this.GetTrailingBoundary());

			// Write out the trailing boundry
			this.requestStream.Write(boundarybytes, 0, boundarybytes.Length);

			// Close the request and file stream
			this.requestStream.Close();

			try
			{
				HttpWebResponse webResponse = (HttpWebResponse)this.httpWebRequest.GetResponse();
				this.responseStream = webResponse.GetResponseStream();
				this.responseReader = new StreamReader(responseStream);
				return responseReader.ReadToEnd();
			}
			catch (WebException e)
			{
				return e.Message;
			}
		}

		private string SubmitMethodGet()
		{
			string dataStr = &quot;&quot;;
			foreach (string[] element in this.datas)
			{
				dataStr += element[0] + &quot;=&quot; + HttpUtility.UrlEncode(element[1]) + &quot;&amp;&quot;;
			}
			if (dataStr.Length &gt; 0)
			dataStr = dataStr.Substring(0, dataStr.Length - 1);

			// Create the web request
			this.httpWebRequest = (HttpWebRequest)WebRequest.Create(this.requestUrl + &quot;?&quot; + dataStr);
			this.httpWebRequest.Method = &quot;GET&quot;;
			this.httpWebRequest.KeepAlive = true;
			this.httpWebRequest.AllowWriteStreamBuffering = true;
			this.httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;

			// Cookies
			this.httpWebRequest.CookieContainer = new CookieContainer();
			if (this.sessionKey != null &amp;&amp; this.sessionKey.Length &gt; 0 &amp;&amp; this.sessionValue != null &amp;&amp; this.sessionValue.Length &gt; 0)
			{
				this.httpWebRequest.CookieContainer.Add(new Cookie(this.sessionKey, this.sessionValue, this.sessionPath, this.sessionDomain));
			}

			try
			{
				HttpWebResponse webResponse = (HttpWebResponse)this.httpWebRequest.GetResponse();
				this.responseStream = webResponse.GetResponseStream();
				this.responseReader = new StreamReader(responseStream);
				return responseReader.ReadToEnd();
			}
			catch (WebException e)
			{
				return e.Message;
			}
		}

		private void StreamWritePostDataPacket()
		{
			byte[] bytes;
			foreach (string[] element in this.datas)
			{
				bytes = Encoding.ASCII.GetBytes(this.GetBoundary());
				this.requestStream.Write(bytes, 0, bytes.Length);
				bytes = this.EncodingGetBytes(string.Format(headerPostDataTemplate, element[0], element[1]));
				this.requestStream.Write(bytes, 0, bytes.Length);
			}
		}

		private void StreamWriteFilePacket()
		{
			byte[] bytes;
			foreach (string[] element in this.files)
			{
				bytes = Encoding.ASCII.GetBytes(this.GetBoundary());
				this.requestStream.Write(bytes, 0, bytes.Length);
				bytes = this.EncodingGetBytes(string.Format(headerFileTemplate, element[0], new FileInfo(element[1]).Name));
				this.requestStream.Write(bytes, 0, bytes.Length);

				// Open up a filestream.
				FileStream fileStream = new FileStream(element[1], FileMode.Open, FileAccess.Read);
				// Use 4096 for the buffer
				byte[] buffer = new byte[4096];
				int bytesRead = 0;
				// Loop through whole file uploading parts in a stream.
				while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
				{
					requestStream.Write(buffer, 0, bytesRead);
					requestStream.Flush();
				}
				fileStream.Close();
			}
		}

		private long GetPostDataPacketLength()
		{
			long length = 0;
			foreach (string[] element in this.datas)
			{
				length += Encoding.ASCII.GetBytes(this.GetBoundary()).Length;
				length += this.EncodingGetBytes(string.Format(headerPostDataTemplate, element[0], new FileInfo(element[1]).Name)).Length;
			}
			return length;
		}

		private long GetFilePacketLength()
		{
			long length = 0;
			foreach (string[] element in this.files)
			{
				length += Encoding.ASCII.GetBytes(this.GetBoundary()).Length;
				length += this.EncodingGetBytes(string.Format(headerFileTemplate, element[0], new FileInfo(element[1]).Name)).Length;
				length += new FileInfo(element[1]).Length;
			}
			return length;
		}

		private string GetBoundary()
		{
			return &quot;\r\n--&quot; + this.boundary + &quot;\r\n&quot;;
		}

		private string GetTrailingBoundary()
		{
			return &quot;\r\n--&quot; + this.boundary + &quot;--\r\n&quot;;
		}

		private byte[] EncodingGetBytes(string packet)
		{
			if (this.encoding.ToLower().Replace(&quot;-&quot;, &quot;&quot;).Equals(&quot;utf7&quot;))
			return System.Text.Encoding.UTF7.GetBytes(packet);
			else if (this.encoding.ToLower().Replace(&quot;-&quot;, &quot;&quot;).Equals(&quot;utf8&quot;))
			return System.Text.Encoding.UTF8.GetBytes(packet);
			else if (this.encoding.ToLower().Replace(&quot;-&quot;, &quot;&quot;).Equals(&quot;utf32&quot;))
			return System.Text.Encoding.UTF32.GetBytes(packet);
			else if (this.encoding.ToLower().Replace(&quot;-&quot;, &quot;&quot;).Equals(&quot;unicode&quot;))
			return System.Text.Encoding.Unicode.GetBytes(packet);
			else if (this.encoding.ToLower().Replace(&quot;-&quot;, &quot;&quot;).Equals(&quot;bigendianunicode&quot;))
			return System.Text.Encoding.BigEndianUnicode.GetBytes(packet);
			else if (this.encoding.ToLower().Replace(&quot;-&quot;, &quot;&quot;).Equals(&quot;ascii&quot;))
			return System.Text.Encoding.ASCII.GetBytes(packet);
			else
			return new byte[] { };
		}
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://kentreez.com/blog/csharp/c-httprequester-class-upload-file-with-post-data/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

