HttpWebRequest/Response Exception
Hi, Im trying to build an app that retrieves real-time fx quotes.
Im getting an exception "cannot access a disposed object" when I try to make a 2nd call to GetResponse() even though I am disposing off it through using statements (I've tried to call Close() manually; this did not solve problem).
Code:
static void Main(string[] args)
{
string sessionID = "xxxxxx";
HttpWebRequest rateRequest = HttpWebRequest.Create(string.Format(@"http://webrates.truefx.com/rates/connect.html?id={0}", sessionID)) as HttpWebRequest;
HttpWebResponse rateResponse;
while (true)
{
using (rateResponse = rateRequest.GetResponse() as HttpWebResponse)
{
if (rateResponse != null)
{
using (StreamReader rateReader = new StreamReader(rateResponse.GetResponseStream()) )
{
Console.WriteLine(rateReader.ReadToEnd());
}
}
}
}
}
Would really appreciate some help!
Re: HttpWebRequest/Response Exception
I believe you need to create a new HttpWebRequest object for each request. You can't recycle an existing one. Try:
Code:
static void Main(string[] args)
{
string sessionID = "xxxxxx";
while (true)
{
HttpWebRequest rateRequest = HttpWebRequest.Create(string.Format(@"http://webrates.truefx.com/rates/connect.html?id={0}", sessionID)) as HttpWebRequest;
HttpWebResponse rateResponse;
using (rateResponse = rateRequest.GetResponse() as HttpWebResponse)
{
if (rateResponse != null)
{
using (StreamReader rateReader = new StreamReader(rateResponse.GetResponseStream()))
{
Console.WriteLine(rateReader.ReadToEnd());
}
}
}
}
}
I put the HttpWebRequest creation code in the scope of the while loop so it will be recreated each time it is needed. I also tested it on my machine and while I got a message of not authorized from the server, no exceptions were generated :)
Re: HttpWebRequest/Response Exception
This worked thank you! :)
Re: HttpWebRequest/Response Exception
i should point out that this code is massively inconsiderate and badly behaved because there's no rate control; it just hammers out a new request as soon as the old one finishes. You should consider adding a timer and making only one request per minute, or longer. I you truly do need fx rate updats more frequently than this, the decent thing to do would be to contact truefx and asking them for the most efficient way to receive currency updats rather than hammering the living daylights out of the free service they provide...