Extend HttpWebRequest Timeout

[日本語]

The default Timeout of HttpWebRequest is 100 seconds.
So, It will timeout if the server response take more than 100 seconds.

If you want to extend the Timeout. You can set The Timeout as your preferrd time.

But If you set the Timeout, You shoud call the timeout before calling “GetRequestStream()”

 

 

using System;
using System.Web;
using System.Net;
using System.Text;
using System.IO;

namespace ConsoleNetFramework
{
class Sample
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(“http://localhost/slow”);

request.Method=”POST”;
byte[] postData = System.Text.Encoding.ASCII.GetBytes(“message=hello”);

 request.Timeout = 3*60*1000; // <– You need to set Timeout here!!
                                                           //  before calling “GetRequestStream()”.

Stream writeStream = request.GetRequestStream();
 request.Timeout = 3*60*1000; // <– If you set Timeout here after calling “GetRequestStream()”.
// it doesn’t work.

writeStream.Write(postData, 0, postData.Length);

HttpWebResponse response;
// Get Response… and happen the TIMEOUT ERROR.
 response = (HttpWebResponse)request.GetResponse(); 

Stream receiveStream = response.GetResponseStream();
StreamReader sr = new System.IO.StreamReader(receiveStream, System.Text.Encoding.GetEncoding(“utf-8”));
Console.WriteLine(sr.ReadToEnd());
}
}
}