关于HttpWebRequest和HttpWebResponse的应用

来源:互联网 发布:淘宝运营面试问题 编辑:程序博客网 时间:2024/04/26 23:16
 1.关于HttpWebRequest和HttpWebResponse的应用

    最近在为公司产品(ASP.NET B/S结构)进行升级的时候遇到了客户的这样一个需求.
    系统提供会议投票这样一种功能,在会议参与者对此次会议所要研究的合同进行研讨之后,系统把参与者的意见(同意,不同意,有条件同意)和意见的详细信息列出,供会议决策者参考,最后由会议决策者输入决策意见.
    其中每一笔合同都包括很多信息,如:法人资料,兄弟公司信息,担保人信息等等,用户迫切需要保存这一系列信息的当前状态.因为这些信息在未来的系统使用过程中可能会发生变更,比如担保人的名称变更等等.
    但是所有的这些信息是由不同的功能结合起来组成的,如果想把这些信息进行汇总,那么重写所有的信息获取方法是不太可行的,所以直接请求页面,从服务器返回的HTML数据流中获取所需内容也许是一个可行的办法.
    首先在程序中维持一个所有信息请求页面地址的列表,然后循环这个列表,进行信息的获取.
    在程序中用到了System.Net, System.IO命名空间.

public string getPageFromURL(string url)
{
 string content = "";
 // Create a new HttpWebRequest object.Make sure that
 // a default proxy is set if you are behind a fure wall.
//其中,HttpWebRequest实例不使用HttpWebRequest的构造函数来创建,二是使用WebRequest的Create方法来创建.
 HttpWebRequest myHttpWebRequest1 =(HttpWebRequest)WebRequest.Create(url);

 //不维持与服务器的请求状态
 myHttpWebRequest1.KeepAlive=false;
//创建一个HttpWebRequest对象
 //Assign the response object of HttpWebRequest to a HttpWebResponse variable./
 HttpWebResponse myHttpWebResponse1;
 try
 {
    //根据微软MSDN上所说:"决不要直接创建HttpWebResponse的实例,要使用HttpWebRequest的GetResponse()方法返回的实例."具体的原因我也不清楚,可能HttpWebResponse类的构造函数中没有实现HttpWebResponse实例的代码吧.
  myHttpWebResponse1 = (HttpWebResponse)myHttpWebRequest1.GetResponse();
  //设置页面的编码模式
  System.Text.Encoding utf8 = System.Text.Encoding.Default;
  Stream streamResponse=myHttpWebResponse1.GetResponseStream();
  StreamReader streamRead = new StreamReader(streamResponse, utf8);

  Char[] readBuff = new Char[256];
    //这里使用了StreamReader的Read()方法,参数意指从0开始读取256个char到readByff中.
    //Read()方法返回值为指定的字符串数组,当达到文件或流的末尾使,方法返回0

  int count = streamRead.Read( readBuff, 0, 256 );
  while (count > 0)
  {
   String outputData = new String(readBuff, 0, count);
   content += outputData;
   count = streamRead.Read(readBuff, 0, 256);
  }
  myHttpWebResponse1.Close();
  return(content);
 }
 catch(WebException ex)
 {
  content = "在请求URL为:" + url + "的页面时产生错误,错误信息为" + ex.ToString();
  return(content);
 }
}

2.使用HttpWebRequest、HttpWebResponse获取网页中文乱码解决方案

我想在程序里面读取一个网页,然后把网页的内容显示出来,开始的时候使用代码如下:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(addr);
// Downloads the XML file from the specified server.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.IO.StreamReader sr = new StreamReader(response.GetResponseStream());
Console.Write(sr.ReadToEnd());
sr.Close();
response.Close();
的一次测试时返回了数据,测试的使用的是一个e文网站。OK,一切顺利,但是换了一个中文
网站问题就出来了,中文居然显示是乱码,晕倒,搞了好长时间也没有搞定。后来研究了StreamReader
类的构造函数,发现有个构造函数是可以指定字符编码格式。好,查文档,HttpWebResponse 中有个
CharacterSet属性是服务器端文件编码格式,把这个设置进去,代码如下:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(addr);
// Downloads the XML file from the specified server.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.IO.StreamReader sr = new StreamReader(response.GetResponseStream(), response.CharacterSet);
Console.Write(sr.ReadToEnd());
sr.Close();
response.Close();
嗯,这回不错,用 http://www.qq39.net 测试一下,居然中文返回的不会乱码了,再用其它的中文网站测试一把。
我哭,http://www.maitian.cn/mt_fz_center/member/index.asp 这个网址返回的中文居然还是乱码。为什么同样
是中文网站,返回的数据会不同呢?应该还是CharacterSet属性的问题。跟踪代码,发现能够正确显示中文的网站
返回的 CharacterSet 属性值是 gb2312,不能正确显示中文的一般是 ISO-8859-1。好,那我就把编码格式都指定
成 gb2312.代码如下:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(addr);
// Downloads the XML file from the specified server.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.IO.StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("gb2312"));
Console.Write(sr.ReadToEnd());
sr.Close();
response.Close();
O, YEAH!这次万事顺利,返回的都是中文,折磨我一天一夜的问题终于解决,心里那个爽呀,嘿嘿。具体的代码如下:
using System;
using System.Xml;
using System.Net;
using System.IO;

public class CSharpHttpExample
{
    public static void Main()
    {
        // Change the Microsoft Internet Information Server (IIS) name in following URL.
        while (true)
        {
            Console.WriteLine("please input url:");
            string addr = Console.ReadLine();

            while (addr.Length == 0)
            {
                Console.WriteLine("please input url:");
                addr = Console.ReadLine();
            }

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(addr); //http://www.qq39.net http://www.maitian.cn/mt_fz_center/member/index.asp

                // Change Username and password.
                //request.Credentials = new NetworkCredential("[username]", "[password]");

                // Downloads the XML file from the specified server.
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Console.WriteLine(response.CharacterSet);
                Console.WriteLine("please input charset:");
                addr = Console.ReadLine();
                //System.IO.BufferedStream bf = new BufferedStream(response.GetResponseStream);
                System.IO.StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding(addr));
                Console.Write(sr.ReadToEnd());
                sr.Close();
                response.Close();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            // Releases the resources of the response.
            Console.Read();
        }
    }
}


 3.

如何使用 HttpWebRequest 类和 HttpWebResponse 类来通过 VisualC # 运行 Exchange 2000 服务器计算机上创建约会项目

 

要在 Visual C#, 是运行 Exchange 2000 计算机上创建约会项目请按照下列步骤: 1. 启动 MicrosoftVisualStudio.NET 或 Microsoft Visual Studio 2005。 2. 在 文件 菜单, 指向 新建 , 然后单击 项目 。 3. 在 VisualC # 项目类型 列表, 单击 控制台应用程序 。

注意 对于 Visual Studio 2005, 单击 VisualC # 列表中 控制台应用程序

VisualStudio.NET 中, 默认情况下创建 Class 1。 在 Visual Studio 2005, Program.cs 创建默认。 4. 在代码窗口, 替换为以下代码:
using System;using System.Net;using System.IO;            namespace WebDavNET{    /// <summary>    /// Summary description for Class1.    /// </summary>    class Class1    {    static void Main(string[] args)    {        try         {            // TODO: Replace with the URL of an object on Exchange Server            string sUri = "http://ExchServer/Exchange/Administrator/Calendar/testappt.eml";                   System.Uri myUri = new System.Uri(sUri);            HttpWebRequest HttpWRequest = (HttpWebRequest)WebRequest.Create(myUri);            string strXMLNSInfo = "xmlns:g=/"DAV:/" " +            " xmlns:e=/"http://schemas.microsoft.com/exchange//"" +            " xmlns:mapi=/"http://schemas.microsoft.com/mapi//"" +            " xmlns:x=/"xml:/" xmlns:cal=/"urn:schemas:calendar:/"" +            " xmlns:dt=/"urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882//"" +            " xmlns:mail=/"urn:schemas:httpmail:/">";            string sQuery = "<?xml version=/"1.0/"?>" +            "<g:propertyupdate " + strXMLNSInfo +            "<g:set>" +            "<g:prop>" +            "<g:contentclass>urn:content-classes:appointment</g:contentclass>" +            "<e:outlookmessageclass>IPM.Appointment</e:outlookmessageclass>" +            "<mail:subject>Appointment Subject</mail:subject>" +            "<cal:location>Appointment Location</cal:location>" +            "<cal:dtstart dt:dt=/"dateTime.tz/">2001-12-27T22:00:00.000Z</cal:dtstart>" +            "<cal:dtend dt:dt=/"dateTime.tz/">2001-12-27T22:30:00.000Z</cal:dtend>" +            "<cal:instancetype dt:dt=/"int/">0</cal:instancetype>" +            "<cal:busystatus>BUSY</cal:busystatus>" +            "<cal:meetingstatus>TENTATIVE</cal:meetingstatus>" +            "<cal:alldayevent dt:dt=/"boolean/">0</cal:alldayevent>" +            "</g:prop>" +            "</g:set>" +            "</g:propertyupdate>";            // Set credentials.            // TODO: Replace with appropriate user credential            NetworkCredential myCred = new NetworkCredential(@"DomainName/UserName", "UserPassword");            CredentialCache myCredentialCache = new CredentialCache();            myCredentialCache.Add(myUri, "Basic", myCred);            HttpWRequest.Credentials = myCredentialCache;            // Set headers.            HttpWRequest.KeepAlive = false;            HttpWRequest.Headers.Set("Pragma", "no-cache");            HttpWRequest.Headers.Set("Translate", "f");            HttpWRequest.ContentType =  "text/xml";            HttpWRequest.ContentLength = sQuery.Length;            //Set the request timeout to 5 minutes.            HttpWRequest.Timeout = 300000;            // set the request method            HttpWRequest.Method = "PROPPATCH";                        // Store the data in a byte array.            byte[] ByteQuery = System.Text.Encoding.ASCII.GetBytes(sQuery);            HttpWRequest.ContentLength = ByteQuery.Length;            Stream QueryStream = HttpWRequest.GetRequestStream();            // Write the data to be posted to the request stream.            QueryStream.Write(ByteQuery,0,ByteQuery.Length);            QueryStream.Close();            // Send the request and get the response.            HttpWebResponse HttpWResponse = (HttpWebResponse)HttpWRequest.GetResponse();            // Get the Status code.            int iStatCode =  (int)HttpWResponse.StatusCode;            string sStatus = iStatCode.ToString();            Console.WriteLine("Status Code: {0}", sStatus);            // Get the request headers            string sReqHeaders = HttpWRequest.Headers.ToString();            Console.WriteLine(sReqHeaders);            // Read the response stream.            Stream strm = HttpWResponse.GetResponseStream();            StreamReader sr = new StreamReader(strm);            string sText = sr.ReadToEnd();            Console.WriteLine("Response: {0}", sText);            // Close the stream.            strm.Close();            // Clean up            myCred = null;            myCredentialCache = null;            HttpWRequest = null;            HttpWResponse = null;            QueryStream = null;            strm = null;            sr = null;               }        catch (Exception e)        {            Console.WriteLine("{0} Exception caught.", e);        }        }    }}
5. 代码, 中搜索 TODO 和然后修改用于环境代码。 6. 按 F 5 键生成并以运行该程序。 7. 请确保已创建约会项目。
 
原创粉丝点击