关于HttpWebRequest详细用法可以参考MSDN和我的另一篇
这个例子只是一个客户端发起请求,服务端简单处理相应的例子。
客户端请求
string reqestMsg = "Tom"; string responseMsg = string.Empty; byte[] buffer = Encoding.UTF8.GetBytes(reqestMsg); try { //把请求地址换成博客园的 如http://www.cnblogs.com 就返回了整个页面数据 HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:6603/WebServer.aspx"); request.Method = "POST"; request.ContentLength = buffer.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(buffer, 0, buffer.Length); } HttpWebResponse resonse = (HttpWebResponse)request.GetResponse(); Stream responseStream = resonse.GetResponseStream(); using (StreamReader sr = new StreamReader(responseStream)) { responseMsg = sr.ReadToEnd(); } resonse.Close(); } catch (Exception ex) { responseMsg = ex.Message; } Response.Write(responseMsg);
服务端相应
string responseMsg = "NO MSG"; if (Request.InputStream != null) { byte[] buffer = new byte[Request.InputStream.Length]; Request.InputStream.Read(buffer, 0, buffer.Length); string msg = Encoding.UTF8.GetString(buffer); msg = msg.Replace("+", "%2B").Replace(" ", "%20"); responseMsg = SayHello(msg); } Response.Write(responseMsg);