本例演示如何向一个WebService发送请求并获取返回值
请求端代码如下,可以使用request.Headers.Add方法,向请求头写入自定义参数
接收方获取方式为
HttpRequest hr = HttpContext.Current.Request;
hr.Headers["cmd1"].ToString()
[WebMethod(Description = "测试")]
public string TestWebRequest(string p1,string p2)
{
string strURL = "http://document.dongjiangoa.com/FlowManageNew/Common/OtherSystem.asmx/TESTPOST";
System.Net.HttpWebRequest request;
request = (System.Net.HttpWebRequest)HttpWebRequest.Create(strURL);
//Post请求方式
request.Method = "POST";
// 内容类型
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("cmd1", Uri.EscapeDataString(p1));
request.Headers.Add("param1", Uri.EscapeDataString(p2));
//这是原始代码:
p1 = p1 + "111";
p2 = p2 + "222";
string paraUrlCoded = "cmd=" + Uri.EscapeDataString(p1) + "¶m=" + Uri.EscapeDataString(p2);
byte[] payload;
//将URL编码后的字符串转化为字节
payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
//设置请求的 ContentLength
request.ContentLength = payload.Length;
//获得请 求流
Stream writer = request.GetRequestStream();
//将请求参数写入流
writer.Write(payload, 0, payload.Length);
// 关闭请求流
writer.Close();
System.Net.HttpWebResponse response;
// 获得响应流
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.Stream s;
s = response.GetResponseStream();
XmlDocument d = new XmlDocument();
d.Load(s);
return d.InnerText;
//MessageBox.Show(d.DocumentElement.InnerText);
}
请求参数写入流中
相应的服务端(接收端)代码
[WebMethod(Description = "测试")]
public string TESTPOST(string cmd, string param)
{
HttpRequest hr = HttpContext.Current.Request;
return "Headers:cmd1:"+hr.Headers["cmd1"].ToString()+";param1:" + hr.Headers["param1"].ToString()+"\r\n"+ "方法名:" + cmd + ";" + "参数名:" + param;
}