在Winform中发HTTP请求(调用WebService服务)

本文详细介绍了如何使用System.NET库手工发送HTTP GET和POST请求。包括构造请求、处理响应及URL编码的过程。GET请求通过拼接URL参数实现,而POST请求则需在请求头中指定内容类型,并将参数作为请求体发送。

手工发送HTTP请求主要是调用System.NET的HttpWEBResponse方法

  手工发送HTTP的GET请求:
string strURL = "http://localhost/Play/CH1/Service1.asmx/doSearch?keyword=";
strURL +=this.textBox1.Text;
System.NET.HttpWEBRequest request;
//创建一个HTTP请求.
request = (System.NET.HttpWebRequest)WEBRequest.Create(strURL);
//request.Method="get";
System.NET.HttpWEBResponse response;
response = (System.NET.HttpWEBResponse)request.GetResponse();
System.IO.Stream s;
s = response.GetResponseStream();
XmlTextReader Reader = newXMLTextReader(s);
Reader.MoveToContent();
string strValue = Reader.ReadInnerXML();
strValue = strValue.Replace("&lt;","<");
strValue = strValue.Replace("&gt;",">");

MessageBox.Show(strValue);
Reader.Close();

  手工发送HTTP的POST请求
string strURL = "http://localhost/Play/CH1/Service1.asmx/doSearch";
System.NET.HttpWEBRequest request;

request = (System.NET.HttpWebRequest)WEBRequest.Create(strURL);
//Post请求方式
request.Method="POST";
//内容类型
request.ContentType="application/x-www-form-urlencoded";
//参数经过URL编码
string paraUrlCoded = System.WEB.HttpUtilITy.UrlEncode("keyword");
paraUrlCoded += "=" + System.WEB.HttpUtilITy.UrlEncode(this.textBox1.Text);
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();
XmlTextReader Reader = newXMLTextReader(s);
Reader.MoveToContent();
string strValue = Reader.ReadInnerXML();
strValue = strValue.Replace("&lt;","<");
strValue = strValue.Replace("&gt;",">");
MessageBox.Show(strValue);
Reader.Close();

  Get请求与Post请求的主要区别在于Post的参数要经过URL编码并在获得请求之前传送,而Get把参数用URL编码后直接附加到请求的URL后面URL编码是一种字符编码格式,它确保传递的参数由一致的文本组成(如将空格编码为"%20")

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值