开发者

This property cannot be set after writing has started! on a C# WebRequest Object

开发者 https://www.devze.com 2022-12-27 11:57 出处:网络
I want to reuse a WebRequest object so that cookies and session would be saved for later request to the server. Below is my code. If i use Post function tw开发者_C百科ice on the second time at

I want to reuse a WebRequest object so that cookies and session would be saved for later request to the server. Below is my code. If i use Post function tw开发者_C百科ice on the second time at

request.ContentLength = byteArray.Length;

it will throw an exception

This property cannot be set after writing has started!

But as you can see

dataStream.Close();

Should close the writing process! Anybody knows what's going on?

static WebRequest request;

public MainForm()
{
    request = WebRequest.Create("http://localhost/admin/admin.php");
}

static string Post(string url, string data) 
{
    request.Method = "POST";
    byte[] byteArray = Encoding.UTF8.GetBytes(data);
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = byteArray.Length;
    Stream dataStream = request.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.Length);
    dataStream.Close();
    WebResponse response = request.GetResponse();
    Console.WriteLine(((HttpWebResponse)response).StatusDescription);
    dataStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(dataStream);
    string responseFromServer = reader.ReadToEnd();
    Console.WriteLine(responseFromServer);
    reader.Close();
    dataStream.Close();
    response.Close();
    request.Abort();
    return responseFromServer;
}


You cannot reuse the WebRequest. Take the returned HttpWebResponse.Cookies, construct a new WebRequest and fill the HttpWebRequest.CookieContainer. (You need to assign a CookieContainer in the first request to get Cookies returned.)

0

精彩评论

暂无评论...
验证码 换一张
取 消