patterncsharpMinor
Sending GET/POST requests in .NET
Viewed 0 times
sendingpostnetgetrequests
Problem
I have a RequestsExtensions class with two functions for sending GET/POST requests.
```
using System;
using System.Net;
using System.Text;
public static class RequestsExtensions
{
///
/// Sending POST request.
///
/// Request Url.
/// Data for request.
/// Response body.
public static string HTTP_POST(string Url, string Data)
{
string Out = String.Empty;
System.Net.WebRequest req = System.Net.WebRequest.Create(Url);
try
{
req.Method = "POST";
req.Timeout = 100000;
req.ContentType = "application/x-www-form-urlencoded";
byte[] sentData = Encoding.UTF8.GetBytes(Data);
req.ContentLength = sentData.Length;
using (System.IO.Stream sendStream = req.GetRequestStream())
{
sendStream.Write(sentData, 0, sentData.Length);
sendStream.Close();
}
System.Net.WebResponse res = req.GetResponse();
System.IO.Stream ReceiveStream = res.GetResponseStream();
using (System.IO.StreamReader sr = new System.IO.StreamReader(ReceiveStream, Encoding.UTF8))
{
Char[] read = new Char[256];
int count = sr.Read(read, 0, 256);
while (count > 0)
{
String str = new String(read, 0, count);
Out += str;
count = sr.Read(read, 0, 256);
}
}
}
catch (ArgumentException ex)
{
Out = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}", ex.Message);
}
catch (WebException ex)
{
Out = str
```
using System;
using System.Net;
using System.Text;
public static class RequestsExtensions
{
///
/// Sending POST request.
///
/// Request Url.
/// Data for request.
/// Response body.
public static string HTTP_POST(string Url, string Data)
{
string Out = String.Empty;
System.Net.WebRequest req = System.Net.WebRequest.Create(Url);
try
{
req.Method = "POST";
req.Timeout = 100000;
req.ContentType = "application/x-www-form-urlencoded";
byte[] sentData = Encoding.UTF8.GetBytes(Data);
req.ContentLength = sentData.Length;
using (System.IO.Stream sendStream = req.GetRequestStream())
{
sendStream.Write(sentData, 0, sentData.Length);
sendStream.Close();
}
System.Net.WebResponse res = req.GetResponse();
System.IO.Stream ReceiveStream = res.GetResponseStream();
using (System.IO.StreamReader sr = new System.IO.StreamReader(ReceiveStream, Encoding.UTF8))
{
Char[] read = new Char[256];
int count = sr.Read(read, 0, 256);
while (count > 0)
{
String str = new String(read, 0, count);
Out += str;
count = sr.Read(read, 0, 256);
}
}
}
catch (ArgumentException ex)
{
Out = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}", ex.Message);
}
catch (WebException ex)
{
Out = str
Solution
First off your methods are not extension methods as the name
Other things I noticed:
-
The use of a magic number here:
-
Your naming convention is a bit weird. Standard naming convention for methods in C# is PascalCase. Also local variables are normally camelCase (your
-
In
-
The way you handle exceptions is less than ideal. The caller of your methods has no easy way to find out if the call actually succeeded or not - except for parsing the return value of the method.
A better way to deal with it is to let exceptions bubble up to the caller and let the caller decide what to do (e.g. terminate the process, retry later, etc.). In addition you could log the exception (requires passing in some kind of logger)
Alternatively you could make the return value an
RequestsExtensions would indicate. Not sure if this intentional or. If you want to make them true extension methods then I'd consider passing the Url parameter as Uri rather than as string.Other things I noticed:
-
The use of a magic number here:
req.Timeout = 100000; - This should be a parameter (maybe with a default value) you can pass in.-
Your naming convention is a bit weird. Standard naming convention for methods in C# is PascalCase. Also local variables are normally camelCase (your
Out variable is not while other variables like req are).-
In
HTTP_POST you use a block-wise read to get the response while in HTTP_GET you simply read to the end of the response stream - why the difference? The HTTP_GET version seems much simpler so why not do it the same way? In fact both those method get a response and read it and deal with the exceptions - this is duplicated code which you should move into a dedicated function which you can then call from both main methods like this:private static string GetResponse(System.Net.WebRequest request)
{
string result = "";
try
{
System.Net.WebResponse resp = req.GetResponse();
using (System.IO.Stream stream = resp.GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(stream))
{
result = sr.ReadToEnd();
sr.Close();
}
}
}
catch
....
return result;
}-
The way you handle exceptions is less than ideal. The caller of your methods has no easy way to find out if the call actually succeeded or not - except for parsing the return value of the method.
A better way to deal with it is to let exceptions bubble up to the caller and let the caller decide what to do (e.g. terminate the process, retry later, etc.). In addition you could log the exception (requires passing in some kind of logger)
Alternatively you could make the return value an
out parameter and return a bool indicating if the call was successful instead if you really want to hide the exceptions from the caller. In this case I'd rename the methods to something like TryHttpPost and TryHttpGetCode Snippets
private static string GetResponse(System.Net.WebRequest request)
{
string result = "";
try
{
System.Net.WebResponse resp = req.GetResponse();
using (System.IO.Stream stream = resp.GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(stream))
{
result = sr.ReadToEnd();
sr.Close();
}
}
}
catch
....
return result;
}Context
StackExchange Code Review Q#49671, answer score: 8
Revisions (0)
No revisions yet.