15 July 2009

HttpWebRequest mit C#

If you want to send data to a website or a webservice the following code should help. If you're using a webservice don't forget the security.
using System.Net;
using System.IO;
 
...
...
 
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("URL");
 
request.Method = "POST";
 
string parameter = "title=" + title.Text + "&" + "text=" + text.Text;
 
byte[] byteArray = Encoding.UTF8.GetBytes(parameter);
 
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
 
try
{
 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 
 if (response.StatusCode == HttpStatusCode.OK)
 {
  dataStream = response.GetResponseStream();
  StreamReader reader = new StreamReader(dataStream);
  status.Text += reader.ReadToEnd();
  response.Close();
 }
 else
 {
  status.Text = "Error";
 }  
}
catch (Exception ex)
{
 status.Text = ex.Message;
}
Post a Comment