码迷,mamicode.com
首页 > Windows程序 > 详细

如何在WinForm中发送HTTP请求

时间:2014-06-18 15:24:00      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:winform   style   class   blog   code   http   

Winform窗体中发送HTTP请求


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

手工发送HTTP的GET请 求:

 1 string strURL = "http://localhost/Play/CH1/Service1.asmx/doSearch?keyword=";
 2 strURL +=this.textBox1.Text;
 3 System.Net.HttpWebRequest request;
 4 // 创建一个HTTP请求
 5 request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
 6 //request.Method="get";
 7 System.Net.HttpWebResponse response;
 8 response = (System.Net.HttpWebResponse)request.GetResponse();
 9 System.IO.Stream s;
10 s = response.GetResponseStream();
11 XmlTextReader Reader = new XmlTextReader(s);
12 Reader.MoveToContent();
13 string strValue = Reader.ReadInnerXml();
14 strValue = strValue.Replace("&lt;","<");
15 strValue = strValue.Replace("&gt;",">");
16 MessageBox.Show(strValue); 
17 Reader.Close();

 

手工发送HTTP的POST请求

 1 string strURL = "http://localhost/Play/CH1/Service1.asmx/doSearch";
 2 System.Net.HttpWebRequest request;
 3 
 4 request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
 5 //Post请求方式
 6 request.Method="POST";
 7 // 内容类型
 8 request.ContentType="application/x-www-form-urlencoded";
 9 // 参数经过URL编码
10 string paraUrlCoded = System.Web.HttpUtility.UrlEncode("keyword");
11 paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(this.textBox1.Text);
12 byte[] payload;
13 //将URL编码后的字符串转化为字节
14 payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
15 //设置请求的 ContentLength 
16 request.ContentLength = payload.Length;
17 //获得请 求流
18 Stream writer = request.GetRequestStream();
19 //将请求参数写入流
20 writer.Write(payload,0,payload.Length);
21 // 关闭请求流
22 writer.Close();
23 System.Net.HttpWebResponse response;
24 // 获得响应流
25 response = (System.Net.HttpWebResponse)request.GetResponse();
26 System.IO.Stream s;
27 s = response.GetResponseStream();
28 XmlTextReader Reader = new XmlTextReader(s);
29 Reader.MoveToContent();
30 string strValue = Reader.ReadInnerXml();
31 strValue = strValue.Replace("&lt;","<");
32 strValue = strValue.Replace("&gt;",">");
33 MessageBox.Show(strValue); 
34 Reader.Close(); 

 

 

如何在WinForm中发送HTTP请求,布布扣,bubuko.com

如何在WinForm中发送HTTP请求

标签:winform   style   class   blog   code   http   

原文地址:http://www.cnblogs.com/MDK-L/p/3791303.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!