29

I wanted to make an HTTP call to a website. I just need to hit the URL and dont want to upload or download any data. What is the easiest and fastest way to do it.

I tried below code but its slow and after 2nd repetitive request it just goes into timeout for 59 secounds and than resume:

WebRequest webRequest = WebRequest.Create("http://ussbazesspre004:9002/DREADD?" + fileName);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = fileName.Length;

Stream os = webRequest.GetRequestStream();
os.Write(buffer, 0, buffer.Length);
os.Close();

Is using the WebClient more efficient??

WebClient web = new WebClient();
web.UploadString(address);

I am using .NET ver 3.5

Adriano Carneiro
  • 57,693
  • 12
  • 90
  • 123
Mayur J
  • 371
  • 1
  • 7
  • 14

3 Answers3

51

You've got some extra stuff in there if you're really just trying to call a website. All you should need is:

WebRequest webRequest = WebRequest.Create("http://ussbazesspre004:9002/DREADD?" + fileName);
WebResponse webResp = webRequest.GetResponse();

If you don't want to wait for a response, you may look at BeginGetResponse to make it asynchronous .

Doozer Blake
  • 7,677
  • 2
  • 29
  • 40
11

If you don't want to upload any data you should use:

webRequest.Method = "GET";

If you really don't care about getting any data back (for instance if you just want to check to see if the page is available) use:

webRequest.Method = "HEAD";

In either case, instead of webRequest.GetRequestStream() use:

WebResponse myWebResponse = webRequest.GetResponse();
Waylon Flinn
  • 19,969
  • 15
  • 70
  • 72
7

WebClient is a shorter and more concise syntax but behind the scenes it uses a WebRequest, so in terms of performance it won't be faster, it will be equivalent. If you want it to be faster you will have to improve the server side script or your network infrastructure. The problem is not on the client side.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    An additional means of achieving greater performance would be to use the 'HEAD' HTTP method, especially if the file being requested is large. However, my guess is that the real problem lies elsewhere. – Waylon Flinn Oct 07 '11 at 14:47