views:

590

answers:

3

I have a HTTP based API which I potentially need to call many times. The problem is that I can't get the request to take less than about 20 seconds, though the same request made through a browser is near instantaneous. The following code illustrates how I have implemented it so far.

WebRequest r = HttpWebRequest.Create("https://example.com/http/command?param=blabla");
var response = r.GetResponse();

One solution would be to make an asynchronous request but I would like to know why it takes so long and if I can avoid it. I have also tried using the WebClient class but I suspect it uses a WebRequest internally.

Update:

Running the following code took about 40 seconds in Release Mode (measured with Stopwatch):

WebRequest g = HttpWebRequest.Create("http://www.google.com");
var response = g.GetResponse();

I'm working at a university where there might be different things in the network configuration affecting the performance, but the direct use of the browser illustrates that it should be near instant.

Update 2:

I uploaded the code to a remote machine and it worked fine so the conclusion must be that the .NET code does something extra compared to the browser or it has problems resolving the address through the university network (proxy issues or something?!).

+1  A: 

Anything to do with the fact you are using https?

ozczecho
+1  A: 

Does your site have an invalid SSL cert? Try adding this

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AlwaysAccept);

//... somewhere AlwaysAccept is defined as:

using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

public bool AlwaysAccept(object sender, X509Certificate certification, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    return true;
}
Philip Rieck
A: 

This problem is similar to another post on StackOverflow: Stackoverflow-2519655(HttpWebrequest is extremely slow)

Most of the time the problem is the Proxy server property. You should set this property to null, otherwise the object will attempt to search for an appropriate proxy server to use before going directly to the source. Note: this property is turn on by default, so you have to explicitly tell the object not to perform this proxy search.

JamesR