博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c# HttpWebRequest与HttpWebResponse
阅读量:4140 次
发布时间:2019-05-25

本文共 14385 字,大约阅读时间需要 47 分钟。

c# HttpWebRequest与HttpWebResponse 
绝技    

如果你想做一些,抓取,或者是自动获取的功能,那么就跟我一起来学习一下Http请求吧。

本文章会对Http请求时的Get和Post方式进行详细的说明,

在请求时的参数怎么发送,怎么带Cookie,怎么设置证书,怎么解决 编码等问题,进行一步一步的解决。

* 如果要使用中间的方法的话,可以访问我的帮助类完全免费开源:

这个类是专门为HTTP的GET和POST请求写的,解决了编码,证书,自动带Cookie等问题。


1.第一招,根据URL地址获取网页信息

   先来看一下代码

get方法 
普通浏览
复制代码
  1. public 
    static 
    string GetUrltoHtml
    (
    string Url,
    string type
    )
  2.         {
  3.             
    try
  4.             {
  5.                 
    System.
    Net.WebRequest wReq = 
    System.
    Net.WebRequest.Create
    (Url
    )
    ;
  6.                 
    // Get the response instance.
  7.                 
    System.
    Net.WebResponse wResp = wReq.GetResponse
    (
    )
    ;
  8.                 
    System.
    IO.Stream respStream = wResp.GetResponseStream
    (
    )
    ;
  9.                 
    // Dim reader As StreamReader = New StreamReader(respStream)
  10.                 
    using 
    (
    System.
    IO.StreamReader reader = 
    new 
    System.
    IO.StreamReader
    (respStream, Encoding.GetEncoding
    (type
    )
    )
    )
  11.                 {
  12.                     
    return reader.ReadToEnd
    (
    )
    ;
  13.                 }
  14.             }
  15.             
    catch 
    (
    System.Exception ex
    )
  16.             {
  17.                 
    //errorMsg = ex.Message;
  18.             }
  19.             
    return 
    ""
    ;
  20.         }

post方法 

普通浏览
复制代码
  1.         
    ///<summary>
  2.         
    ///采用https协议访问网络
  3.         
    ///</summary>
  4.         
    ///<param name="URL">url地址</param>
  5.         
    ///<param name="strPostdata">发送的数据</param>
  6.         
    ///<returns></returns>
  7.         
    public 
    string OpenReadWithHttps
    (
    string URL, 
    string strPostdata, 
    string strEncoding
    )
  8.         {
  9.             Encoding encoding = Encoding.Default
    ;
  10.             HttpWebRequest request = 
    (HttpWebRequest
    )WebRequest.Create
    (URL
    )
    ;
  11.             request.Method = 
    "post"
    ;
  12.             request.Accept = 
    "text/html, application/xhtml+xml, */*"
    ;
  13.             request.ContentType = 
    "application/x-www-form-urlencoded"
    ;
  14.             
    byte
    [
    ] buffer = encoding.GetBytes
    (strPostdata
    )
    ;
  15.             request.ContentLength = buffer.Length
    ;
  16.             request.GetRequestStream
    (
    ).Write
    (buffer, 
    0, buffer.Length
    )
    ;
  17.             HttpWebResponse response = 
    (HttpWebResponse
    )request.GetResponse
    (
    )
    ;
  18.             
    using
    ( StreamReader reader = 
    new StreamReader
    (response.GetResponseStream
    (
    )
    System.
    Text.Encoding.GetEncoding
    (strEncoding
    )
    )
    )
  19.               {
  20.                    
    return reader.ReadToEnd
    (
    )
    ;
  21.               }
  22.         }

这招是入门第一式, 特点:


   1.最简单最直观的一种,入门课程。


   2.适应于明文,无需登录,无需任何验证就可以进入的页面。


   3.获取的数据类型为HTML文档。


   4.请求方法为Get/Post


2.第二招,根据URL地址获取需要验证证书才能访问的网页信息


   先来看一下代码


get方法 

普通浏览
复制代码
  1.          /回调验证证书问题
  2.         
    public 
    bool CheckValidationResult
    (
    object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors
    )
  3.         {   
  4.            
    // 总是接受    
  5.             
    return 
    true
    ;
  6.         }
  7.         
    /// <summary>
  8.         
    /// 传入URL返回网页的html代码
  9.         
    /// </summary>
  10.         
    /// <param name="Url">URL</param>
  11.         
    /// <returns></returns>
  12.         
    public 
    string GetUrltoHtml
    (
    string Url
    )
  13.         {
  14.             StringBuilder content = 
    new StringBuilder
    (
    )
    ;
  15.             
    try
  16.             {
  17.                 
    //这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
  18.                 ServicePointManager.ServerCertificateValidationCallback = 
    new 
    System.
    Net.
    Security.RemoteCertificateValidationCallback
    (CheckValidationResult
    )
    ;
  19.                 
    // 与指定URL创建HTTP请求
  20.                 HttpWebRequest request = 
    (HttpWebRequest
    )WebRequest.Create
    (Url
    )
    ;
  21.                 
    //创建证书文件
  22.                 X509Certificate objx509 = 
    new X509Certificate
    (
    Application.StartupPath + 
    "\\123.cer"
    )
    ;
  23.                 
    //添加到请求里
  24.                 request.ClientCertificates.Add
    (objx509
    )
    ;
  25.                 
    // 获取对应HTTP请求的响应
  26.                 HttpWebResponse response = 
    (HttpWebResponse
    )request.GetResponse
    (
    )
    ;
  27.                 
    // 获取响应流
  28.                 Stream responseStream = response.GetResponseStream
    (
    )
    ;
  29.                 
    // 对接响应流(以"GBK"字符集)
  30.                 StreamReader sReader = 
    new StreamReader
    (responseStream, Encoding.GetEncoding
    (
    "utf-8"
    )
    )
    ;
  31.                 
    // 开始读取数据
  32.                 Char
    [
    ] sReaderBuffer = 
    new Char
    [
    256
    ]
    ;
  33.                 
    int count = sReader.Read
    (sReaderBuffer, 
    0
    256
    )
    ;
  34.                 
    while 
    (count > 
    0
    )
  35.                 {
  36.                     String tempStr = 
    new String
    (sReaderBuffer, 
    0, count
    )
    ;
  37.                     content.Append
    (tempStr
    )
    ;
  38.                     count = sReader.Read
    (sReaderBuffer, 
    0
    256
    )
    ;
  39.                 }
  40.                 
    // 读取结束
  41.                 sReader.Close
    (
    )
    ;
  42.             }
  43.             
    catch 
    (Exception
    )
  44.             {
  45.                 content = 
    new StringBuilder
    (
    "Runtime Error"
    )
    ;
  46.             }
  47.             
    return content.ToString
    (
    )
    ;
  48.         }

post方法 

普通浏览
复制代码
  1.          
    //回调验证证书问题
  2.         
    public 
    bool CheckValidationResult
    (
    object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors
    )
  3.         {
  4.             
    // 总是接受    
  5.             
    return 
    true
    ;
  6.         }
  7.         
    ///<summary>
  8.         
    ///采用https协议访问网络
  9.         
    ///</summary>
  10.         
    ///<param name="URL">url地址</param>
  11.         
    ///<param name="strPostdata">发送的数据</param>
  12.         
    ///<returns></returns>
  13.         
    public 
    string OpenReadWithHttps
    (
    string URL, 
    string strPostdata, 
    string strEncoding
    )
  14.         {
  15.             
    // 这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
  16.             ServicePointManager.ServerCertificateValidationCallback = 
    new 
    System.
    Net.
    Security.RemoteCertificateValidationCallback
    (CheckValidationResult
    )
    ;
  17.             Encoding encoding = Encoding.Default
    ;
  18.             HttpWebRequest request = 
    (HttpWebRequest
    )WebRequest.Create
    (URL
    )
    ;
  19.             
    //创建证书文件
  20.             X509Certificate objx509 = 
    new X509Certificate
    (
    Application.StartupPath + 
    "\\123.cer"
    )
    ;
  21.             
    //加载Cookie
  22.             request.CookieContainer = 
    new CookieContainer
    (
    )
    ;
  23.             
    //添加到请求里
  24.             request.ClientCertificates.Add
    (objx509
    )
    ;
  25.             request.Method = 
    "post"
    ;
  26.             request.Accept = 
    "text/html, application/xhtml+xml, */*"
    ;
  27.             request.ContentType = 
    "application/x-www-form-urlencoded"
    ;
  28.             
    byte
    [
    ] buffer = encoding.GetBytes
    (strPostdata
    )
    ;
  29.             request.ContentLength = buffer.Length
    ;
  30.             request.GetRequestStream
    (
    ).Write
    (buffer, 
    0, buffer.Length
    )
    ;
  31.             HttpWebResponse response = 
    (HttpWebResponse
    )request.GetResponse
    (
    )
    ;
  32.             
    using 
    (StreamReader reader = 
    new StreamReader
    (response.GetResponseStream
    (
    )
    System.
    Text.Encoding.GetEncoding
    (strEncoding
    )
    )
    )
  33.                {
  34.                    
    return reader.ReadToEnd
    (
    )
    ;
  35.                }
  36.         }

这招是学会算是进了大门了,凡是需要验证证书才能进入的页面都可以使用这个方法进入,我使用的是证书回调验证的方式,证书验证是否通过在客户端验证,这样的话我们就可以使用自己定义一个方法来验证了,有的人会说那也不清楚是怎么样验证的啊,其它很简单,代码是自己写的为什么要那么难为自己呢,直接返回一个True不就完了,永远都是验证通过,这样就可以无视证书的存在了, 特点:


   1.入门前的小难题,初级课程。


   2.适应于无需登录,明文但需要验证证书才能访问的页面。


   3.获取的数据类型为HTML文档。


   4.请求方法为Get/Post


3.第三招,根据URL地址获取需要登录才能访问的网页信息


        我们先来分析一下这种类型的网页,需要登录才能访问的网页,其它呢也是一种验证,验证什么呢,验证客户端是否登录,是否具用相应的凭证,需要登录的都要验证SessionID这是每一个需要登录的页面都需要验证的,那我们怎么做的,我们第一步就是要得存在Cookie里面的数据包括SessionID,那怎么得到呢,这个方法很多,使用ID9或者是火狐浏览器很容易就能得到,可以参考我的文章


  这里面针对ID9有详细的说明。

如果我们得到了登录的Cookie信息之后那个再去访问相应的页面就会非常的简单了,其它说白了就是把本地的Cookie信息在请求的时候捎带过去就行了。

   看代码

get方法 
普通浏览
复制代码
  1.         
    /// <summary>
  2.         
    /// 传入URL返回网页的html代码带有证书的方法
  3.         
    /// </summary>
  4.         
    /// <param name="Url">URL</param>
  5.         
    /// <returns></returns>
  6.         
    public 
    string GetUrltoHtml
    (
    string Url
    )
  7.         {
  8.             StringBuilder content = 
    new StringBuilder
    (
    )
    ;
  9.             
    try
  10.             {
  11.                 
    // 与指定URL创建HTTP请求
  12.                 HttpWebRequest request = 
    (HttpWebRequest
    )WebRequest.Create
    (Url
    )
    ;
  13.                 request.UserAgent = 
    "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; BOIE9;ZHCN)"
    ;
  14.                 request.Method = 
    "GET"
    ;
  15.                 request.Accept = 
    "*/*"
    ;
  16.                 
    //如果方法验证网页来源就加上这一句如果不验证那就可以不写了
  17.                 request.Referer = 
    "http://sufei.cnblogs.com"
    ;
  18.                 CookieContainer objcok = 
    new CookieContainer
    (
    )
    ;
  19.                 objcok.Add
    (
    new Uri
    (
    "http://sufei.cnblogs.com"
    )
    new Cookie
    (
    "键"
    "值"
    )
    )
    ;
  20.                 objcok.Add
    (
    new Uri
    (
    "http://sufei.cnblogs.com"
    )
    new Cookie
    (
    "键"
    "值"
    )
    )
    ;
  21.                 objcok.Add
    (
    new Uri
    (
    "http://sufei.cnblogs.com"
    )
    new Cookie
    (
    "sidi_sessionid"
    "360A748941D055BEE8C960168C3D4233"
    )
    )
    ;
  22.                 request.CookieContainer = objcok
    ;
  23.                 
    //不保持连接
  24.                 request.KeepAlive = 
    true
    ;
  25.                 
    // 获取对应HTTP请求的响应
  26.                 HttpWebResponse response = 
    (HttpWebResponse
    )request.GetResponse
    (
    )
    ;
  27.                 
    // 获取响应流
  28.                 Stream responseStream = response.GetResponseStream
    (
    )
    ;
  29.                 
    // 对接响应流(以"GBK"字符集)
  30.                 StreamReader sReader = 
    new StreamReader
    (responseStream, Encoding.GetEncoding
    (
    "gb2312"
    )
    )
    ;
  31.                 
    // 开始读取数据
  32.                 Char
    [
    ] sReaderBuffer = 
    new Char
    [
    256
    ]
    ;
  33.                 
    int count = sReader.Read
    (sReaderBuffer, 
    0
    256
    )
    ;
  34.                 
    while 
    (count > 
    0
    )
  35.                 {
  36.                     String tempStr = 
    new String
    (sReaderBuffer, 
    0, count
    )
    ;
  37.                     content.Append
    (tempStr
    )
    ;
  38.                     count = sReader.Read
    (sReaderBuffer, 
    0
    256
    )
    ;
  39.                 }
  40.                 
    // 读取结束
  41.                 sReader.Close
    (
    )
    ;
  42.             }
  43.             
    catch 
    (Exception
    )
  44.             {
  45.                 content = 
    new StringBuilder
    (
    "Runtime Error"
    )
    ;
  46.             }
  47.             
    return content.ToString
    (
    )
    ;
  48.         }

post方法。 

普通浏览
复制代码
  1.          
    ///<summary>
  2.         
    ///采用https协议访问网络
  3.         
    ///</summary>
  4.         
    ///<param name="URL">url地址</param>
  5.         
    ///<param name="strPostdata">发送的数据</param>
  6.         
    ///<returns></returns>
  7.         
    public 
    string OpenReadWithHttps
    (
    string URL, 
    string strPostdata
    )
  8.         {
  9.             Encoding encoding = Encoding.Default
    ;
  10.             HttpWebRequest request = 
    (HttpWebRequest
    )WebRequest.Create
    (URL
    )
    ;
  11.             request.Method = 
    "post"
    ;
  12.             request.Accept = 
    "text/html, application/xhtml+xml, */*"
    ;
  13.             request.ContentType = 
    "application/x-www-form-urlencoded"
    ;
  14.             CookieContainer objcok = 
    new CookieContainer
    (
    )
    ;
  15.             objcok.Add
    (
    new Uri
    (
    "http://sufei.cnblogs.com"
    )
    new Cookie
    (
    "键"
    "值"
    )
    )
    ;
  16.             objcok.Add
    (
    new Uri
    (
    "http://sufei.cnblogs.com"
    )
    new Cookie
    (
    "键"
    "值"
    )
    )
    ;
  17.             objcok.Add
    (
    new Uri
    (
    "http://sufei.cnblogs.com"
    )
    new Cookie
    (
    "sidi_sessionid"
    "360A748941D055BEE8C960168C3D4233"
    )
    )
    ;
  18.             request.CookieContainer = objcok
    ;
  19.             
    byte
    [
    ] buffer = encoding.GetBytes
    (strPostdata
    )
    ;
  20.             request.ContentLength = buffer.Length
    ;
  21.             request.GetRequestStream
    (
    ).Write
    (buffer, 
    0, buffer.Length
    )
    ;
  22.             HttpWebResponse response = 
    (HttpWebResponse
    )request.GetResponse
    (
    )
    ;
  23.             StreamReader reader = 
    new StreamReader
    (response.GetResponseStream
    (
    )
    System.
    Text.Encoding.GetEncoding
    (
    "utf-8"
    )
    )
    ;
  24.             
    return reader.ReadToEnd
    (
    )
    ;
  25.         }

特点:


   1.还算有点水类型的,练习成功后可以小牛一把。


   2.适应于需要登录才能访问的页面。


   3.获取的数据类型为HTML文档。


   4.请求方法为Get/Post


总结一下,其它基本的技能就这几个部分,如果再深入的话那就是基本技能的组合了


比如,


1. 先用Get或者Post方法登录然后取得Cookie再去访问页面得到信息,这种其它也是上面技能的组合,


这里需要以请求后做这样一步
普通浏览
复制代码
  1. response.Cookies
这就是在你请求后可以得到当次Cookie的方法,直接取得返回给上一个方法使用就行了,上面我们都是自己构造的,在这里直接使用这个Cookie就可以了。


2.如果我们碰到需要登录而且还要验证证书的网页怎么办,其它这个也很简单把我们上面的方法综合 一下就行了


如下代码这里我以Get为例子Post例子也是同样的方法 

普通浏览
复制代码
  1.         
    /// <summary>
  2.         
    /// 传入URL返回网页的html代码
  3.         
    /// </summary>
  4.         
    /// <param name="Url">URL</param>
  5.         
    /// <returns></returns>
  6.         
    public 
    string GetUrltoHtml
    (
    string Url
    )
  7.         {
  8.             StringBuilder content = 
    new StringBuilder
    (
    )
    ;
  9.             
    try
  10.             {
  11.                 
    //这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
  12.                 ServicePointManager.ServerCertificateValidationCallback = 
    new 
    System.
    Net.
    Security.RemoteCertificateValidationCallback
    (CheckValidationResult
    )
    ;
  13.                 
    // 与指定URL创建HTTP请求
  14.                 HttpWebRequest request = 
    (HttpWebRequest
    )WebRequest.Create
    (Url
    )
    ;
  15.                 
    //创建证书文件
  16.                 X509Certificate objx509 = 
    new X509Certificate
    (
    Application.StartupPath + 
    "\\123.cer"
    )
    ;
  17.                 
    //添加到请求里
  18.                 request.ClientCertificates.Add
    (objx509
    )
    ;
  19.                 CookieContainer objcok = 
    new CookieContainer
    (
    )
    ;
  20.                 objcok.Add
    (
    new Uri
    (
    "http://www.cnblogs.com"
    )
    new Cookie
    (
    "键"
    "值"
    )
    )
    ;
  21.                 objcok.Add
    (
    new Uri
    (
    "http://www.cnblogs.com"
    )
    new Cookie
    (
    "键"
    "值"
    )
    )
    ;
  22.                 objcok.Add
    (
    new Uri
    (
    "http://www.cnblogs.com"
    )
    new Cookie
    (
    "sidi_sessionid"
    "360A748941D055BEE8C960168C3D4233"
    )
    )
    ;
  23.                 request.CookieContainer = objcok
    ;
  24.                 
    // 获取对应HTTP请求的响应
  25.                 HttpWebResponse response = 
    (HttpWebResponse
    )request.GetResponse
    (
    )
    ;
  26.                 
    // 获取响应流
  27.                 Stream responseStream = response.GetResponseStream
    (
    )
    ;
  28.                 
    // 对接响应流(以"GBK"字符集)
  29.                 StreamReader sReader = 
    new StreamReader
    (responseStream, Encoding.GetEncoding
    (
    "utf-8"
    )
    )
    ;
  30.                 
    // 开始读取数据
  31.                 Char
    [
    ] sReaderBuffer = 
    new Char
    [
    256
    ]
    ;
  32.                 
    int count = sReader.Read
    (sReaderBuffer, 
    0
    256
    )
    ;
  33.                 
    while 
    (count > 
    0
    )
  34.                 {
  35.                     String tempStr = 
    new String
    (sReaderBuffer, 
    0, count
    )
    ;
  36.                     content.Append
    (tempStr
    )
    ;
  37.                     count = sReader.Read
    (sReaderBuffer, 
    0
    256
    )
    ;
  38.                 }
  39.                 
    // 读取结束
  40.                 sReader.Close
    (
    )
    ;
  41.             }
  42.             
    catch 
    (Exception
    )
  43.             {
  44.                 content = 
    new StringBuilder
    (
    "Runtime Error"
    )
    ;
  45.             }
  46.             
    return content.ToString
    (
    )
    ;
  47.         }

3.如果我们碰到那种需要验证网页来源的方法应该怎么办呢,这种情况其它是有些程序员会想到你可能会使用程序,自动来获取网页信息,为了防止就使用页面来源来验证,就是说只要不是从他们所在页面或是域名过来的请求就不接受,有的是直接验证来源的IP,这些都可以使用下面一句来进入,这主要是这个地址是可以直接伪造的 

普通浏览
复制代码
  1. request.Referer = <a href=
    "http://sufei.cnblogs.com"><a href=\
    "http://sufei.cnblogs.com/\" target=\"_blank\">http://sufei.cnblogs.com</a></a>;

呵呵其它很简单因为这个地址可以直接修改。但是如果服务器上验证的是来源的URL那就完了,我们就得去修改数据包了,这个有点难度暂时不讨论。


4.提供一些与这个例子相配置的方法


    过滤HTML标签的方法
普通浏览
复制代码
  1.         /// <summary>
  2.         /// 过滤html标签
  3.         /// </summary>
  4.         /// <param name="strHtml
    ">html的内容</param>
  5.         /// <returns></returns>
  6.         public static string StripHTML(string stringToStrip)
  7.         {
  8.             // paring using RegEx           //
  9.             stringToStrip = Regex.Replace(stringToStrip, "</p
    (?:\\s*
    )>
    (?:\\s*
    )<p
    (?:\\s*
    )>
    ", "\n\n
    ", RegexOptions.IgnoreCase | RegexOptions.Compiled);
  10.             stringToStrip = Regex.Replace(stringToStrip, "
  11. ", "\n
    ", RegexOptions.IgnoreCase | RegexOptions.Compiled);
  12.             stringToStrip = Regex.Replace(stringToStrip, "\
    ""
    "''", RegexOptions.IgnoreCase | RegexOptions.Compiled
    )
    ;
  13.             stringToStrip = StripHtmlXmlTags
    (stringToStrip
    )
    ;
  14.             
    return stringToStrip
    ;
  15.         }
  16.         
    private 
    static 
    string StripHtmlXmlTags
    (
    string content
    )
  17.         {
  18.             
    return Regex.Replace
    (content, 
    "<[^>]+>"
    "", RegexOptions.IgnoreCase | RegexOptions.Compiled
    )
    ;
  19.         }
URL转化的方法

普通浏览
复制代码
  1. #region 转化 URL
  2.         
    public 
    static 
    string URLDecode
    (
    string text
    )
  3.         {
  4.             
    return HttpUtility.UrlDecode
    (text, Encoding.Default
    )
    ;
  5.         }
  6.         
    public 
    static 
    string URLEncode
    (
    string text
    )
  7.         {
  8.             
    return HttpUtility.UrlEncode
    (text, Encoding.Default
    )
    ;
  9.         }
  10.         
    #endregion

提供一个实际例子,这个是使用IP138来查询手机号码归属地的方法,其它在我的上一次文章里都有,在这里我再放上来是方便大家阅读,这方面的技术其它研究起来很有意思,希望大家多提建议,我相信应该还有更多更好,更完善的方法,在这里给大家提供一个参考吧。感谢支持


上例子

普通浏览
复制代码
  1.         
    /// <summary>
  2.         
    /// 输入手机号码得到归属地信息
  3.         
    /// </summary>
  4.         
    /// <param name="number">手机号码</param>
  5.         
    /// <returns>数组类型0为归属地,1卡类型,2区 号,3邮 编</returns>
  6.         
    public 
    static 
    string
    [
    ] getTelldate
    (
    string number
    )
  7.         {
  8.             
    try
  9.             {
  10.                 
    string strSource = GetUrltoHtml
    (
    "http://www.ip138.com:8080/search.asp?action=mobile&mobile=" + number.Trim
    (
    )
    )
    ;
  11.                 
    //归属地
  12.                 strSource = strSource.Substring
    (strSource.IndexOf
    (number
    )
    )
    ;
  13.                 strSource = StripHTML
    (strSource
    )
    ;
  14.                 strSource = strSource.Replace
    (
    "\r"
    ""
    )
    ;
  15.                 strSource = strSource.Replace
    (
    "\n"
    ""
    )
    ;
  16.                 strSource = strSource.Replace
    (
    "\t"
    ""
    )
    ;
  17.                 strSource = strSource.Replace
    (
    " "
    ""
    )
    ;
  18.                 strSource = strSource.Replace
    (
    "-->"
    ""
    )
    ;
  19.                 
    string
    [
    ] strnumber = strSource.Split
    (
    new 
    string
    [
    ] { 
    "归属地"
    "卡类型"
    "邮 编"
    "区 号"
    "更详细"
    "卡号" }, StringSplitOptions.RemoveEmptyEntries
    )
    ;
  20.                 
    string
    [
    ] strnumber1 = 
    null
    ;
  21.                 
    if 
    (strnumber.Length > 
    4
    )
  22.                 {
  23.                     strnumber1 = 
    new 
    string
    [
    ] { strnumber
    [
    1
    ].Trim
    (
    ), strnumber
    [
    2
    ].Trim
    (
    ), strnumber
    [
    3
    ].Trim
    (
    ), strnumber
    [
    4
    ].Trim
    (
    ) }
    ;
  24.                 }
  25.                 
    return strnumber1
    ;
  26.             }
  27.             
    catch 
    (Exception
    )
  28.             {
  29.                 
    return 
    null
    ;
  30.             }
  31.         }
这个例子写是不怎么样,些地方是可以简化的,这个接口而且可以直接使用Xml得到,但我在这里的重点是让一些新手看看方法和思路风凉啊,呵呵

第四招,通过Socket访问
普通浏览
复制代码
  1.         
    ///<summary>
  2.         
    /// 请求的公共类用来向服务器发送请求
  3.         
    ///</summary>
  4.         
    ///<param name="strSMSRequest">发送请求的字符串</param>
  5.         
    ///<returns>返回的是请求的信息</returns>
  6.         
    private 
    static 
    string SMSrequest
    (
    string strSMSRequest
    )
  7.         {
  8.             
    byte
    [
    ] data = 
    new 
    byte
    [
    1024
    ]
    ;
  9.             
    string stringData = 
    null
    ;
  10.             IPHostEntry gist = Dns.GetHostByName
    (
    "www.110.cn"
    )
    ;
  11.             IPAddress ip = gist.AddressList
    [
    0
    ]
    ;
  12.             
    //得到IP 
  13.             IPEndPoint ipEnd = 
    new IPEndPoint
    (ip, 
    3121
    )
    ;
  14.             
    //默认80端口号 
  15.             Socket socket = 
    new Socket
    (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp
    )
    ;
  16.             
    //使用tcp协议 stream类型 
  17.             
    try
  18.             {
  19.                 socket.Connect
    (ipEnd
    )
    ;
  20.             }
  21.             
    catch 
    (SocketException ex
    )
  22.             {
  23.                 
    return 
    "Fail to connect server\r\n" + ex.ToString
    (
    )
    ;
  24.             }
  25.             
    string path = strSMSRequest.ToString
    (
    ).Trim
    (
    )
    ;
  26.             StringBuilder buf = 
    new StringBuilder
    (
    )
    ;
  27.             
    //buf.Append("GET ").Append(path).Append(" HTTP/1.0\r\n");
  28.             
    //buf.Append("Content-Type: application/x-www-form-urlencoded\r\n");
  29.             
    //buf.Append("\r\n");
  30.             
    byte
    [
    ] ms = 
    System.
    Text.UTF8Encoding.UTF8.GetBytes
    (buf.ToString
    (
    )
    )
    ;
  31.             
    //提交请求的信息
  32.             socket.Send
    (ms
    )
    ;
  33.             
    //接收返回 
  34.             
    string strSms = 
    ""
    ;
  35.             
    int recv = 
    0
    ;
  36.             
    do
  37.             {
  38.                 recv = socket.Receive
    (data
    )
    ;
  39.                 stringData = Encoding.ASCII.GetString
    (data, 
    0, recv
    )
    ;
  40.                 
    //如果请求的页面meta中指定了页面的encoding为gb2312则需要使用对应的Encoding来对字节进行转换() 
  41.                 strSms = strSms + stringData
    ;
  42.                 
    //strSms += recv.ToString();
  43.             }
  44.             
    while 
    (recv != 
    0
    )
    ;
  45.             socket.Shutdown
    (SocketShutdown.Both
    )
    ;
  46.             socket.Close
    (
    )
    ;
  47.             
    return strSms
    ;
  48.         }
你可能感兴趣的文章
"Cannot allocate memory" OutofMemory when call Ant to build Polish project in Tomcat
查看>>
dumpcap抓包(python)
查看>>
查看文件是否被其他进程访问
查看>>
字符编码详解
查看>>
python使用dpkt分析wireshak报文(Modbus规约)
查看>>
css中的IFC
查看>>
CentOS 6.5下 mysql用户root登录不了
查看>>
windows + tomcat 部署web服务 http 改为https访问方法
查看>>
Windows系统下Apache 服务器启动以及过程中产生问题的解决办法
查看>>
Oracle服务说明
查看>>
异常收集(三):Missing artifact com.oracle:ojdbc6:jar:1.0 两种解决方案
查看>>
异常收集(四):Plugin execution not covered by lifecycle configuration
查看>>
异常收集(五):Io 异常: The Network Adapter could not establish the connection
查看>>
JSP中的转义字符
查看>>
SQLException: The user specified as a definer ('root'@'%') does not exist
查看>>
Linux 操作指令收集
查看>>
CentOS 7下卸载MySQL方式(转)
查看>>
CentOS7 安装MySQL 5.6.43
查看>>
使用Java 导入/导出 Excel ----Jakarta POI
查看>>
本地tomcat 服务器内存不足
查看>>