注意,这个方法仅仅适用于:该post页面处于websercive 站点下,或者是与webservice同属于一个主站点,即在iis里属于同一主站点的同级虚拟目录。
protected void btnSynData_Click(object sender, EventArgs e) { string wsUrl = "http://127.0.0.1:1113/yingxiao/clfbxd.asmx/huixie"; //注意:huixie 是webservice的方法名 string postData = "我是谁"; HttpConnectToServer(wsUrl, postData); } /// <summary> /// 发送消息到ws服务器 /// </summary> /// <param name="ServerPage"></param> /// <param name="strXml"></param> /// <returns></returns> public string HttpConnectToServer(string ServerPage, string strXml) { string postData = "strXml=" + strXml; byte[] dataArray = Encoding.Default.GetBytes(postData); //创建请求 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ServerPage); request.Credentials = CredentialCache.DefaultCredentials; request.CookieContainer = new CookieContainer(); request.Method = "POST"; request.ContentLength = dataArray.Length; request.ContentType = "application/x-www-form-urlencoded"; //创建输入流 Stream dataStream = null; try { dataStream = request.GetRequestStream(); } catch (Exception) { return null;//连接服务器失败 } //发送请求 dataStream.Write(dataArray, 0, dataArray.Length); dataStream.Close(); //读取返回消息 string res = string.Empty; try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); res = reader.ReadToEnd(); reader.Close(); } catch (Exception ex) { throw new Exception(ex.Message); } return res; }
参考:http://www.jb51.net/article/34589.htm