我需要实现一个应用程序来发布字符串,如HttpRequest来指定IP地址,然后以httpRespons形式接收答案。 这是发送代码
WebRequest request = WebRequest.Create("http://192.168.1.10");
request.Method = "POST";
string postData = "string I want to post";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
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();
richTextBox1.AppendText(((HttpWebResponse)response).StatusDescription);
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
richTextBox1.AppendText(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
这段代码好吗?
答案 0 :(得分:0)
代码是正确的,但我认为StreamReader reader = new StreamReader(dataStream);
应附加编码:StreamReader reader = new StreamReader(dataStream,encoding);