Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download a string via HTTP from .NET 4.5?

Tags:

c#

.net

.net-4.5

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 Tasks, 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?

like image 610
Vilx- Avatar asked Jan 31 '13 13:01

Vilx-


2 Answers

HttpWebRequest class is not deprecated, only its constructors are.

To cite the documentation:

Do not use the HttpWebRequest constructor. Use the WebRequest.Create method to initialize new HttpWebRequest objects. If the scheme for the Uniform Resource Identifier (URI) is http:// or https://, Create returns an HttpWebRequest object.

like image 128
GSerg Avatar answered Sep 21 '22 21:09

GSerg


Only the constructor is deprecated, not the HttpWebRequest class itself. Use WebRequest.Create to create an instance of HttpWebRequest.

like image 23
dgvid Avatar answered Sep 17 '22 21:09

dgvid