2

I've written code about httpwebrequest and httpwebresponse . I need to send data to server but got this exception "This operation cannot be performed after request has been submitted". see the following code:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://"+remoteServer+":8080/");
request.Credentials = CredentialCache.DefaultCredentials;
//Stream NewReqstream = request.GetRequestStream();
request.Method = "POST";
//request.ContentLength = cmd.Length;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine("Connected..");

// Send the command
//clientSocket.Send(cmd);

Stream NewReqstream = request.GetRequestStream(); //<-- Error here
NewReqstream.Write(cmd, 0, cmd.Length);
NewReqstream.Close();
Peacelyk
  • 1,126
  • 4
  • 24
  • 48
soundy
  • 307
  • 4
  • 8
  • 25

3 Answers3

3

when you get the response stream the request is submitted so you can not the operation there...

Try it like:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://"+remoteServer+":8080/");
request.Credentials = CredentialCache.DefaultCredentials;
//Stream NewReqstream = request.GetRequestStream();
request.Method = "POST";
//request.ContentLength = cmd.Length;

// Send the command
//clientSocket.Send(cmd);

Stream NewReqstream = request.GetRequestStream(); //<-- Error here
NewReqstream.Write(cmd, 0, cmd.Length);
NewReqstream.Close();

// Get the response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine("Connected..");
Legy
  • 411
  • 3
  • 9
2

The exception tells you what you need to know; HTTP is request => response, so if you have asked for the response (GetResponse()) you have implicitly said "my request is complete; give me the response". Move the GetRequestStream() code above the GetResponse().

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • especcially you have to move all the streamoperations on the request streem obove GetResponse(), too – Legy Aug 02 '11 at 07:02
0

Make request before response. For anyone needs multiple requests and responses make sure using different variables for each request and response such as req1 res1, req2 res2...

esenkaya
  • 99
  • 4