我已经编写了关于httpwebrequesthttpwebresponse的代码。我需要将数据发送到服务器,但出现以下异常:“提交请求后无法执行此操作”。请参见以下代码:

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();

最佳答案

当您获得响应流时,请求将被提交,因此您不能在那里执行操作…
试试看:

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

10-07 16:25