Tuesday, December 6, 2011

C# HTTP Post

1:  using System.Net;  
2:  using System.IO;  
3:  ...  
4:  ...  
5:  public string HTTPPost(string uri, string parameters)  
6:  {  
7:    WebRequest webRequest = WebRequest.Create(uri);  
8:    webRequest.ContentType = "application/x-www-form-urlencoded";  
9:    webRequest.Method = "POST";  
10:    byte[] bytes = Encoding.ASCII.GetBytes(parameters);  
11:    Stream os = null;  
12:    try  
13:    {  
14:      webRequest.ContentLength = bytes.Length;  
15:      os = webRequest.GetRequestStream();  
16:      os.Write(bytes, 0, bytes.Length);  
17:    }  
18:    catch (WebException ex)  
19:    {  
20:     MessageBox.Show(ex.Message, "Request error");  
21:    }  
22:    finally  
23:    {  
24:      if (os != null)  
25:      {  
26:        os.Close();  
27:      }  
28:    }  
29:    try  
30:    {  
31:      WebResponse webResponse = webRequest.GetResponse();  
32:      if (webResponse == null) return null;  
33:      StreamReader sr = new StreamReader(webResponse.GetResponseStream());  
34:      return sr.ReadToEnd().Trim();  
35:    }  
36:    catch (WebException ex)  
37:    {  
38:      MessageBox.Show(ex.Message, "Response error");  
39:    }  
40:    return null;  
41:  }  

No comments:

Post a Comment