I've got a very simple need - my C# code needs to connect to a remote server via HTTP and download a string. A trivial GET request, nothing more.
To ensure that my application remains responsive I also want to impose a timeout (say, 3 seconds) on the operation.
My first thought was to use System.Net.WebClient
, but that doesn't support any timeouts.
Then I wanted to try the good old System.Net.HttpWebRequest
, but alas - since .NET 4.5 it's been marked as obsolete!
So, what can I use? I checked out the System.Net.Http
namespace, but it only allows asynchronous usage, forces to use Task
s, and generally only adds a dozen different layers of abstraction without really adding any new functionality (since it uses the same old System.Net.HttpWebRequest
underneath anyway)
I don't want asynchronous stuff, I don't want to involve other threads, I don't want to involve the Tasks framework, I don't want tons of wrappers.
What is the correct way to do this in .NET 4.5?
HttpWebRequest
class is not deprecated, only its constructors are.
To cite the documentation:
Do not use the
HttpWebRequest
constructor. Use theWebRequest.Create
method to initialize newHttpWebRequest
objects. If the scheme for the Uniform Resource Identifier (URI) ishttp://
orhttps://
,Create
returns anHttpWebRequest
object.
Only the constructor is deprecated, not the HttpWebRequest class itself. Use WebRequest.Create to create an instance of HttpWebRequest.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With