To send/post Data using a WebRequest in C# and VB.NET you can use the following snippet.

Sample C#

public static string WebrequestWithPost(string url, Encoding dataEncoding, string dataToPost, string contentType = @"application/x-www-form-urlencoded")
{
	var postDataAsByteArray = dataEncoding.GetBytes(dataToPost);
	var returnValue = String.Empty;
	try
	{
		var webRequest = WebRequest.CreateHttp(url);  //change to: var webRequest = (HttpWebRequest)WebRequest.Create(url); if you are your .NET Version is lower than 4.5
		if (webRequest != null)
		{
			webRequest.AllowAutoRedirect = false;
			webRequest.Method = "POST";
			webRequest.ContentType = contentType;
			webRequest.ContentLength = postDataAsByteArray.Length;
			using (var requestDataStream = webRequest.GetRequestStream())
			{
				requestDataStream.Write(postDataAsByteArray, 0, postDataAsByteArray.Length);
				requestDataStream.Close();
				using (var response = webRequest.GetResponse())
				{
					using (var responseDataStream = response.GetResponseStream())
					{
						if (responseDataStream != null)
						{
							using (var responseDataStreamReader = new StreamReader(responseDataStream))
							{
								returnValue = responseDataStreamReader.ReadToEnd();
								responseDataStreamReader.Close();
							}
							responseDataStream.Close();
						}
					}
					response.Close();
				}
				requestDataStream.Close();
			}
		}
	}
	catch (WebException ex)
	{
		if (ex.Status == WebExceptionStatus.ProtocolError)
		{
			var response = ((HttpWebResponse)ex.Response);
			//handle this your own way.
			Console.WriteLine("Webexception! Statuscode: {0}, Description: {1}",(int)response.StatusCode,response.StatusDescription);
		}
	}
	catch(Exception ex) 
	{
		//handle this your own way, something serious happened here.
		Console.WriteLine(ex.Message);
	}
	return returnValue;
}

Sample VB.NET

Public Shared Function WebrequestWithPost(ByVal url As String, ByVal dataEncoding As Encoding, ByVal dataToPost As String, ByVal contentType As String) As String
    Dim postDataAsByteArray As Byte() = dataEncoding.GetBytes(dataToPost)
    Dim returnValue As String = String.Empty
    Try
        Dim webRequest As HttpWebRequest = WebRequest.CreateHttp(url)  'change to: dim webRequest as var = DirectCast(WebRequest.Create(url), HttpWebRequest) if you are your .NET Version is lower than 4.5
        If (Not (webRequest) Is Nothing) Then
            webRequest.AllowAutoRedirect = false
            webRequest.Method = "POST"
            webRequest.ContentType = contentType
            webRequest.ContentLength = postDataAsByteArray.Length
            Dim requestDataStream As Stream = webRequest.GetRequestStream
            requestDataStream.Write(postDataAsByteArray, 0, postDataAsByteArray.Length)
            requestDataStream.Close
            Dim response As Webresponse = webRequest.GetResponse
            Dim responseDataStream As Stream = response.GetResponseStream
            If (Not (responseDataStream) Is Nothing) Then
                Dim responseDataStreamReader As StreamReader = New StreamReader(responseDataStream)
                returnValue = responseDataStreamReader.ReadToEnd
                responseDataStreamReader.Close
                responseDataStream.Close
            End If
            response.Close
            requestDataStream.Close
        End If
    Catch ex As WebException
        If (ex.Status = WebExceptionStatus.ProtocolError) Then
            Dim response As HttpWebResponse = CType(ex.Response,HttpWebResponse)
            'handle this your own way.
            Console.WriteLine("Webexception! Statuscode: {0}, Description: {1}", CType(response.StatusCode,Integer), response.StatusDescription)
        End If
    Catch ex As Exception
        'handle this your own way, something serious happened here.
        Console.WriteLine(ex.Message)
    End Try
    Return returnValue
End Function

FOR MORE INFORMATIONS SEE THE MSDN: How to: Send Data Using the WebRequest Class

2 thought on “How to send Data using a WebRequest in C# and VB.NET”

Leave a Reply