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

来源:互联网 发布:天地盖纸盒尺寸算法 编辑:程序博客网 时间:2024/06/07 07:05

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

手工发送HTTPGET:

C# code

              /////////////////////////////////////////////////////////////////////////////

     ////向服务器发出申请

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";默认为“get”

/////////////////////////////////////////////////////////////////////////////

//////服务器对上面请求的返回结果。由于是web service,返回是xml文件,所以使用下面的方式接收显示

System.Net.HttpWebResponse response;

response = (System.Net.HttpWebResponse)request.GetResponse();

System.IO.Stream s;

s = response.GetResponseStream();

XmlTextReader Reader =new XmlTextReader(s);

Reader.MoveToContent();

string strValue = Reader.ReadInnerXml();

strValue = strValue.Replace("&lt;","<");

strValue = strValue.Replace("&gt;",">");

MessageBox.Show(strValue);

Reader.Close();

 




手工发送HTTPPOST请求

C# code

           

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 =new XmlTextReader(s);

Reader.MoveToContent();

string strValue = Reader.ReadInnerXml();

strValue = strValue.Replace("&lt;","<");

strValue = strValue.Replace("&gt;",">");

MessageBox.Show(strValue);

Reader.Close();

 

 

 

再如(一般网页的接收):

   WebRequest request = WebRequest.Create("http://www.baidu.com/s?wd=张学友");
   WebResponse response = request.GetResponse();
   StreamReader reader = new StreamReader(response.GetResponseStream(),    Encoding.GetEncoding("gb2312"));

   tb.Text = reader.ReadToEnd();

   reader.Close();
   reader.Dispose();
   response.Close();

/////////////////////////////////////////////////////////////////////////////

传送请求