tags:

views:

218

answers:

1

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 twice 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;
}
+4  A: 

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.)

dtb
What about sessions? (is it the same with cookie?)
EBAGHAKI
Sessions are usually implemented using cookies.
dtb
I though that php sessions are a server side thing! so they are base on cookie?
EBAGHAKI
PHP sessions depend on a PHP Session ID. This is usually transmitted as cookie or appended to the query string.
dtb