Friday, 11 May 2012

Beginning .Net , C# Tips : Post data to remote server or URL in C# Programming

There are situations where you want to post data to remote server and other external URL.
We can do this using System.Net namespace.
In this sample example we have this "http://www.dummydomain.com/pagename.aspx" URL and we want to post query string data like "pageid=1&search=.net" and capture response of this in our code.
We are using HttpWebRequest and HttpWebResponse class for this.


C# Example :
Uri url = new Uri("http://www.dummydomain.com/pagename.aspx");
string strParameter = "pageid=1&search=.net";
string data = string.Format("{0}", strParameter);
if (url.Scheme == Uri.UriSchemeHttp)
{
    //Create Request for given url
    System.Net.HttpWebRequest objRequest =(System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
    //Set Request Method
    objRequest.Method = System.Net.WebRequestMethods.Http.Post;
    objRequest.ContentLength = data.Length;
    objRequest.ContentType = "application/x-www-form-urlencoded";
    //Write request stream
    System.IO.StreamWriter objWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());
    objWriter.Write(data);
    objWriter.Close();
    //Get Response from url
    System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();
    //Read Response
    System.IO.StreamReader objReader = new System.IO.StreamReader(objResponse.GetResponseStream());
    string result = objReader.ReadToEnd();
    objResponse.Close();
    pnlScreen.GroupingText = result;
}

VB.net Example :
Dim url As New Uri("http://www.dummydomain.com/pagename.aspx")
Dim strParameter As String = "pageid=1&search=.net"
Dim data As String = String.Format("{0}", strParameter)
If url.Scheme = Uri.UriSchemeHttp Then
    'Create Request for given url
    Dim objRequest As System.Net.HttpWebRequest = DirectCast(System.Net.HttpWebRequest.Create(url), System.Net.HttpWebRequest)
    'Set Request Method
    objRequest.Method = System.Net.WebRequestMethods.Http.Post
    objRequest.ContentLength = data.Length
    objRequest.ContentType = "application/x-www-form-urlencoded"
    'Write request stream
    Dim objWriter As New System.IO.StreamWriter(objRequest.GetRequestStream())
    objWriter.Write(data)
    objWriter.Close()
    'Get Response from url
    Dim objResponse As System.Net.HttpWebResponse = DirectCast(objRequest.GetResponse(), System.Net.HttpWebResponse)
    'Read Response
    Dim objReader As New System.IO.StreamReader(objResponse.GetResponseStream())
    Dim result As String = objReader.ReadToEnd()
    objResponse.Close()
    pnlScreen.GroupingText = result
End If

No comments:

Post a Comment