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 "" URL and we want to post query string data like "pageid=1&" and capture response of this in our code.
We are using HttpWebRequest and HttpWebResponse class for this.

C# Example :
Uri url = new Uri("");
string strParameter = "pageid=1&";
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());
    //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();
    pnlScreen.GroupingText = result;
} Example :
Dim url As New Uri("")
Dim strParameter As String = "pageid=1&"
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())
    '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()
    pnlScreen.GroupingText = result
End If

No comments:

Post a Comment