HttpWebRequest WebResponse 对象简单了解

1.HTTP亦即Hpyer Text Transfer Protocal的缩写,它是现代互联网上最重要的一种网络协议,超文本传输协议位于TCP/IP协议的应用层,是一个面向   无连接、简单、快速的C/S结构的协议 。HTTP的工作过程大体上分连接、请求、响应和断开连接

2..NET类库中提供了WebRequest和WebResponse就是利用这两个类实现的网络功能

 HttpWebRequest:HttpWebRequest 类对 WebRequest 中定义的属性和方法提供支持,也对使用户能够直接与使用

                           HTTP 的服务器交互的附加 属性和方法提供支持。

                           http://msdn.microsoft.com/zh-cn/library/system.net.httpwebrequest.connection(v=VS.80).aspx

WebResponse 类是 abstract 基类,协议特定的响应类从该抽象基类派生。应用程序可以使用 WebResponse 类的实例以协议不可知的方式参与请求和响应事务,而从 WebResponse 派生的协议特定的类携带请求的详细信息

                           http://msdn.microsoft.com/zh-cn/library/system.net.webresponse(v=VS.80).aspx

3.简单应用:

     导入命名空间:using System.Net   using System.IO 

    程序使用 HTTP 协议和服务器交互主要是进行数据的提交,通常数据的提交是通过 GET 和 POST 两种方式

    //创建一个url新的httpwebrequest 对象 

    HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:1782/WebForm1.aspx?");

   //设置myHttpWebRequest 对象属性

    myHttpWebRequest.Method = "post"

    myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";

   myHttpWebRequest.UserAgent = ".NET Framework Client";

    //输入参数 id=中文和Econding

    string inputData = System.Console.ReadLine(); 

   //创建utf-8 或者GB2312 来处理中文 

   // 处理英文就是这个就可以

  //ASCIIEncoding encoding = new ASCIIEncoding();

   Encoding myEncoding = Encoding.GetEncoding("utf-8");

  byte[] byteinputdata = myEncoding.GetBytes(inputData);

  //写入当前流对象发送个服务器

  myHttpWebRequest.ContentLength = byteinputdata.Length;

  Stream newStream = myHttpWebRequest.GetRequestStream();

  newStream.Write(byteinputdata, 0, byteinputdata.Length);  

  newStream.Close();

 //获取服务器响应的结果(根据条件获取对象解析返回结果)

    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

    Stream streamResponse = myHttpWebResponse.GetResponseStream();  

    StreamReader streamRead = new StreamReader(streamResponse);       

    Char[] readBuff = new Char[256];  

    int count = streamRead.Read(readBuff, 0, 256);

    System.Console.WriteLine("\nThe contents of HTML Page are :\n");    

     while (count > 0)            

    {               

      String outputData = new String(readBuff, 0, count);   

      System.Console.Write(outputData);              

      count = streamRead.Read(readBuff, 0, 256);      

     }            

    streamRead.Close();          

    streamResponse.Close();

   myHttpWebResponse.Close();

原文地址:https://www.cnblogs.com/linsu/p/2276124.html