Stream was not writable error when accessing response stream

I have following code (C#) for reading contents from a given url:


private string GetData(string url)
{
//Initialization
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
//This time, our method is GET.
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
using (StreamWriter stOut = new StreamWriter(response.GetResponseStream(), System.Text.Encoding.ASCII))
{
string postData = null;
stOut.Write(postData);
return postData;
}
}
else
{
throw new Exception(string.Format("Error, statuscode: {0}\r\n{1}", response.StatusCode.ToString(), response.StatusDescription));
}
}

But sometime the function will throw error “Stream was not writable” when accessing the response stream, the status code returned is HttpStatusCode.OK, but just cannot access the response stream. On some URLs, the code works fine.

After struggling for a while, I finally found a solution to the error, it turns out that I have to set the Credentials for the request, and with following modification the “Stream was not writable” error was gone and the function works as expected.


request.ContentType = "application/x-www-form-urlencoded";
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s