How to make a Http Web Request properly using C#
//..
private HttpWebRequest _httpwebrequest;
//..
private void button1_Click(object sender, EventArgs e)
{
	Thread t = new Thread(new ThreadStart(Test));
	t.IsBackground = true;
	t.Start();
}
public void Test()
{
	Dictionary<String, String> dict = new Dictionary<String, String>();
	dict.Add("test1", "123");
	dict.Add("test2", "456");
	dict.Add("test3", "789");
	PostRequest("http://localhost/mywebsite/index", dict);
}
private void PostRequest(String url, Dictionary<String, String> parameters)
{
	String postData = "";
 
	foreach (String key in parameters.Keys)
		postData += HttpUtility.UrlEncode(key) + "="
			  + HttpUtility.UrlEncode(parameters[key]) + "&";
	postData = postData.Remove(postData.Length - 1);
 
	_httpwebrequest = (HttpWebRequest)HttpWebRequest.Create(url);
	_httpwebrequest.Method = "POST";
 
	byte[] data = Encoding.ASCII.GetBytes(postData);
 
	_httpwebrequest.ContentType = "application/x-www-form-urlencoded";
	_httpwebrequest.ContentLength = data.Length;
 
	Stream requestStream = _httpwebrequest.GetRequestStream();
	requestStream.Write(data, 0, data.Length);
	requestStream.Close();
 
	_httpwebrequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);
}
private void EndWebRequest(IAsyncResult result)
{
	HttpWebResponse hwr = (HttpWebResponse)_httpwebrequest.EndGetResponse(result);
 
	Stream response = hwr.GetResponseStream();
 
	StreamReader sr = new StreamReader(response, Encoding.Default);
 
	Invoke((MethodInvoker)delegate
	{
		textBox1.Text = sr.ReadToEnd();
	});
 
	sr.Close();
	response.Close();
}
Categories: C# Tags: , , , ,
%d bloggers like this: