HttpWebRequest类详解

HttpWebRequest类与HttpRequest类的区别。
       HttpRequest类的对象用于服务器端,获取客户端传来的请求的信息,包括HTTP报文传送过来的所有信息。而HttpWebRequest用于客户端,拼接请求的HTTP报文并发送等。
       HttpWebRequest这个类非常强大,强大的地方在于它封装了几乎HTTP请求报文里需要用到的东西,以致于能够能够发送任意的HTTP请求并获得服务器响应(Response)信息。采集信息常用到这个类。在学习这个类之前,首先有必要了解下HTTP方面的知识。
      Http ebRequest和HttpWebResponse类是用于发送和接收HTTP数据的最好选择。它们支持一系列有用的属性。这两个类位 于System.Net命名空间,默认情况下这个类对于控制台程序来说是可访问的。请注意,HttpWebRequest对象不是利用new关键字通过构 造函数来创建的,而是利用工厂机制(factory mechanism)通过Create()方法来创建的。另外,你可能预计需要显式地调用一个“Send”方法,实际上不需要。接下来调用 HttpWebRequest.GetResponse()方法返回的是一个HttpWebResponse对象。你可以把HTTP响应的数据流 (stream)绑定到一个StreamReader对象,然后就可以通过ReadToEnd()方法把整个HTTP响应作为一个字符串取回。也可以通过 StreamReader.ReadLine()方法逐行取回HTTP响应的内容。

       HttpWebRequest的KeepAlive默认是true,如果使用的时候仅仅只是关闭流,不关闭网卡上的通道的话,第二个请求在TCP没有关闭的情况下是走同一个通道,此时本机的TCP通道就会抛异常出来,这是本机抛的错误。所以除了关闭本机的IO资源外,还要关闭网络资源。需要把KeepAlive设置成false就可以了。TCP通信结束后会自动关闭该请求所使用的通道。

    必须手动释放httpwebrequest,webresponse,StreamReader,stream等,,否则:一旦出错就会卡很长一段时间。

  简单请求实例

class Program
    {
        static void Main(string[] args)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.baidu.com");    //创建一个请求示例
            HttpWebResponse response  = (HttpWebResponse)request.GetResponse();  //获取响应,即发送请求
            Stream responseStream = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
            string html = streamReader.ReadToEnd();
            Console.WriteLine(html);

            Console.ReadKey();
        }
    }

//调用新浪天气预报
    public string GetWeather(string city)
    {
        string weatherHtml = string.Empty;
        //转换输入参数的编码类型
        string cityInfo = HttpUtility.UrlEncode(city,System.Text.UnicodeEncoding.GetEncoding("GB2312"));
        //初始化新的webRequst
        HttpWebRequest weatherRequest = (HttpWebRequest)WebRequest.Create("http://php.weather.sina.com.cn/search.php?city="+cityInfo);
        
        HttpWebResponse weatherResponse = (HttpWebResponse)weatherRequest.GetResponse();
        //从Internet资源返回数据流
        Stream weatherStream = weatherResponse.GetResponseStream();
        //读取数据流
        StreamReader weatherStreamReader = new StreamReader(weatherStream,System.Text.Encoding.Default);
        //读取数据
        weatherHtml = weatherStreamReader.ReadToEnd();
        weatherStreamReader.Close();
        weatherStream.Close();
        weatherResponse.Close();
        //针对不同的网站查看html源文件
        return weatherHtml;
    }
下面是模拟上传。。 注意路径不能写错,否则在对流进行操作时,Write,就会报错:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:9170/upload/test");
class Program   //客户端
    {
        /** 
         * 如果要在客户端向服务器上传文件,我们就必须模拟一个POST multipart/form-data类型的请求 
         * Content-Type必须是multipart/form-data。 
         * 以multipart/form-data编码的POST请求格式与application/x-www-form-urlencoded完全不同 
         * multipart/form-data需要首先在HTTP请求头设置一个分隔符,例如7d4a6d158c9: 
         * 我们模拟的提交要设定 content-type不同于非含附件的post时候的content-type 
         * 这里需要: ("Content-Type", "multipart/form-data; boundary=ABCD"); 
         * 然后,将每个字段用“--7d4a6d158c9”分隔,最后一个“--7d4a6d158c9--”表示结束。 
         * 例如,要上传一个title字段"Today"和一个文件C:\1.txt,HTTP正文如下: 
         *  
         * --7d4a6d158c9 
         * Content-Disposition: form-data; name="title" 
         * \r\n\r\n 
         * Today 
         * --7d4a6d158c9 
         * Content-Disposition: form-data; name="1.txt"; filename="C:\1.txt" 
         * Content-Type: text/plain 
         * 如果是图片Content-Type: application/octet-stream 
         * \r\n\r\n 
         * <这里是1.txt文件的内容> 
         * --7d4a6d158c9 
         * \r\n 
         * 请注意,每一行都必须以\r\n结束value前面必须有2个\r\n,包括最后一行。 
        */
        static void Main(string[] args)
        {
            string boundary = "----------" + DateTime.Now.Ticks.ToString("x");//元素分割标记 
            StringBuilder sb = new StringBuilder();
            sb.Append("--" + boundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"file1\"; filename=\"D:\\upload.xml" + "\"");
            sb.Append("\r\n");
            sb.Append("Content-Type: application/octet-stream");
            sb.Append("\r\n");
            sb.Append("\r\n");//value前面必须有2个换行  

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:9170/upload/test");
            request.ContentType = "multipart/form-data; boundary=" + boundary;//其他地方的boundary要比这里多--  
            request.Method = "POST";

            FileStream fileStream = new FileStream(@"D:\123.xml", FileMode.OpenOrCreate, FileAccess.Read);

            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sb.ToString());
            byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
            //http请求总长度  
            request.ContentLength = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
            Stream requestStream = request.GetRequestStream(); 
            requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
            byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                requestStream.Write(buffer, 0, bytesRead);
            }
            fileStream.Dispose();
            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
            WebResponse webResponse2 = request.GetResponse();
            Stream htmlStream = webResponse2.GetResponseStream();
            string HTML = GetHtml(htmlStream, "UTF-8");
            Console.WriteLine(HTML);
            htmlStream.Dispose();
        }
  }
服务端
public ActionResult Test()
        {
            HttpRequest request = System.Web.HttpContext.Current.Request;
            HttpFileCollection FileCollect = request.Files;
            if (FileCollect.Count > 0)          //如果集合的数量大于0
            {
                foreach (string str in FileCollect)
                {
                    HttpPostedFile FileSave = FileCollect[str];  //用key获取单个文件对象HttpPostedFile
                    string imgName = DateTime.Now.ToString("yyyyMMddhhmmss");
                    string AbsolutePath = FileSave.FileName;
                    FileSave.SaveAs(AbsolutePath);              //将上传的东西保存
                }
            }
            return Content("键值对数目:" + FileCollect.Count);
        }




猜你喜欢

转载自blog.csdn.net/qq_34571519/article/details/78720834