본문 바로가기

내가 하는일/.NET C#

HttpClient.cs C# 자바의httpclient를 C#으로 옮겨보자

using System;
using System.Net;
using System.Collections;
using System.IO;
namespace XPost
{
	public class HTTPClient
	{
		string url;
		public enum Method { POST, GET };
		private bool requestExecuted = false;
		private Method method = Method.POST; 
		private System.Net.HttpStatusCode retstatus;
		private string cookies = null;
		private string referer = null;
		private string ua = null;
		private WebResponse response;
		private ArrayList nameValuePairs = new ArrayList();
		public void setMethod(HTTPClient.Method m) {
			this.method = m;
		}
		public HTTPClient(string url) {
			this.url = url;
		}
		public void executeRequest() {
			if(this.requestExecuted) {
				return;
			}
			WebRequest wr = null;
			if(Method.POST == this.method) {
				wr = WebRequest.Create(this.url);
				wr.Method = "POST";
				((System.Net.HttpWebRequest)wr).ContentType = "application/x-www-form-urlencoded";
			} else {
				bool fst = true;
				string turl = this.url + "?";
				foreach(string[] pair in nameValuePairs) {
					if(!fst) {
						turl = turl + "&";
					} else {
						fst = false;
					}
					turl = turl + pair[0] + "=" + pair[1];
				}
				wr = WebRequest.Create(turl);
			}
			if(this.cookies != null && !this.cookies.Equals("")) {
				wr.Headers.Set("Cookie", this.cookies);
			}
			if(this.referer != null && !this.referer.Equals("") && wr is System.Net.HttpWebRequest) {
				((HttpWebRequest)wr).Referer = this.referer;
			}
			if(this.ua != null && !this.ua.Equals("")) {
				wr.Headers.Set("User-Agent", this.ua); 
			}
			System.IO.StreamWriter sw = new System.IO.StreamWriter( wr.GetRequestStream());
			bool first = true;
			foreach(string[] pair in nameValuePairs) {
				if(!first) {
					sw.Write("&");
				} else {
					first = false;
				}
				sw.Write(pair[0] + "=" + pair[1]);
			}
			sw.Close();
			WebResponse resp = wr.GetResponse();
			this.response = resp;
			this.retstatus = ((System.Net.HttpWebResponse) this.response).StatusCode;
			this.requestExecuted = true;			
		}
		public void WriteResponseToConsole() {
			if(this.response != null) {
				Console.WriteLine((new StreamReader(this.response.GetResponseStream())).ReadToEnd());
			}
		}
		public void setReferer(string r) {
			this.referer = r;
		}
		public System.Net.HttpStatusCode getResponseCode() {
			return this.retstatus;
		}
		public string getReturnedCookies() {
			if(!this.requestExecuted) {
				return null;
			}
			return this.response.Headers.Get("Cookie");
		}
		public void setNewCookies(string s) {
			this.cookies = s;
		}
		public void addNameValuePair(string name, string val) {
			string[] pair = {	System.Web.HttpUtility.UrlEncode( name),
								System.Web.HttpUtility.UrlEncode( val)};
			this.nameValuePairs.Add(pair);
		}
	}
}