Timeout Problem when Calling GetResponse()

Hello,

I am trying to use the HttpWebResponse and HttpWebRequest to connect to a web address. I am expecting back XML from the address. I can access the web address and successfully get back XML when I connect to it using my web browser but when I try and access the address using the GetResponse method I get a timeout. Is there a setting I am missing that would cause a timeout?

Here is my code:



HttpWebRequest restRequest =

(HttpWebRequest)WebRequest.Create("http://api.search.yahoo.com/WebSearchService/V1/webSearch?results=10&start=1&appid=MY_ID&query=sony&format=html&language=en");

restRequest.Method = "POST";

restRequest.ContentType = "application/x-www-form-urlencoded";

try

{

HttpWebResponse restResponse =

(HttpWebResponse) restRequest.GetResponse();

return restResponse.GetResponseStream();

}

catch(Exception e)

{

throw e;

}


[1329 byte] By [StevenR] at [2007-12-17]
# 1
Why are you setting the
restRequest.ContentType = "application/x-www-form-urlencoded";?

Can you try without that?

DurgaprasadGorti at 2007-9-9 > top of Msdn Tech,.NET Development,.NET Framework Networking and Communication...
# 2
I commented out that line and I still get a timeout.
StevenR at 2007-9-9 > top of Msdn Tech,.NET Development,.NET Framework Networking and Communication...
# 3

You have made some mistakes in your call ordering. You should get the request stream and write your data to the request stream before calling GetResponse. Take a look at my code snippet below for the correct way to use HttpWebRequest/HttpWebResponse.



try
{

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

request.Method = "POST";

request.ContentType = "application/x-www-form-urlencoded";

Stream requestStream = request.GetRequestStream();

requestStream.Write(<YOUR DATA GOES HERE>);

requestStream.Close();

HttpWebResponse response = request.GetResponse() as HttpWebResponse;

Stream responseStream = response.GetResponseStream();

int count = 0;
byte [] buffer = new byte [512];

count = responseStream.Read(buffer,0,buffer.Length);

while (count > 0) {
//do something with the buffer (copy it into a sting or write it to a file)

count = responseStream.Read(buffer,0,buffer.Length);
}

responseStream.Close();

response.Close();


}
catch(Exception ex)
{
Console.WriteLine(ex);
}

JonCole at 2007-9-9 > top of Msdn Tech,.NET Development,.NET Framework Networking and Communication...
# 4
One other thing. If you don't have any data to upload, you can get the request stream and close it immediately.
JonCole at 2007-9-9 > top of Msdn Tech,.NET Development,.NET Framework Networking and Communication...

.NET Development

Site Classified