string url = "http://localhost/BOOK/CH3/FirstServicecs.asmx/HelloWorld"; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); //POST方式请求 req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; string strname= System.Web.HttpUtility.UrlEncode("name"); strname = strname + "=" + System.Web.HttpUtility.UrlEncode(textBox1.Text); byte[] payload;//将URL编码后的字符串转化为字节 payload = System.Text.Encoding.UTF8.GetBytes(strname); req.ContentLength = payload.Length; Stream writer = req.GetRequestStream(); writer.Write(payload, 0, payload.Length); writer.Close(); HttpWebResponse response = (HttpWebResponse)req.GetResponse(); System.IO.Stream s; s = response.GetResponseStream(); XmlTextReader reader =new XmlTextReader(s); reader.MoveToContent(); label1.Text = reader.ReadInnerXml(); reader.Close(); using System;using System.Web;using System.Net;using System.IO;using System.Text;namespace SendMessage{
public bool SendMsg(MsgInfo msg){//create requesttry{WebRequest req = WebRequest.Create("http://your_post_url");
//set the request parameter req.Method = "POST";req.ContentType = "application/x-www-form-urlencoded";
//querystring '?msg=xxx&type=0'string strQuery = "msg=";strQuery += HttpUtility.UrlEncode(msg);strQuery += "&type=0";
string dataSend = strQuery;req.ContentLength = dataSend.Length;
byte [] buff = Encoding.UTF8.GetBytes(dataSend); Stream reqStream = req.GetRequestStream();reqStream.Write(buff, 0, buff.Length);reqStream.Close();
WebResponse rep = req.GetResponse();Stream repStream = rep.GetResponseStream();Encoding enc = Encoding.GetEncoding("utf-8");StreamReader sr = new StreamReader(repStream, enc);
Char[] read = new Char[256];sr.Read(read, 0, 256);
return true;}catch(NotSupportedException ns){return false; }}
}
string url = "http://localhost:21240/ChangeHair/Receive.aspx?aa=5";//发送到的页面的地址 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
//读取一个图片 FileStream fs = new FileStream(Server.MapPath("~/NET基础知识.doc"), System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] filecontent = new byte[fs.Length]; fs.Read(filecontent, 0, filecontent.Length); fs.Close(); fs.Dispose();
//将图片转换成base64编码的流 string a = Convert.ToBase64String(filecontent); //读取base64编码流,发送 byte[] requestBytes = System.Text.Encoding.Default.GetBytes(a);
req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = requestBytes.Length; Stream requestStream = req.GetRequestStream(); requestStream.Write(requestBytes, 0, requestBytes.Length); requestStream.Close();
//接收返回参数,到string backstr HttpWebResponse res = (HttpWebResponse)req.GetResponse(); StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default); string backstr = sr.ReadToEnd(); sr.Close(); res.Close(); //输出参数 Response.Write(backstr);