代码改变世界

C# HttpWebRequest 绝技

  苏飞  阅读(83733)  评论(42编辑  收藏  举报

        查看全文,这里不再更新,最新版请大家访问如下地址:

     http://www.sufeinet.com/thread-6-1-1.html

如果要使用中间的方法的话,可以访问我的帮助类完全免费开源:C# HttpHelper,帮助类,真正的Httprequest请求时无视编码,无视证书,无视Cookie,网页抓取

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

   先来看一下代码

get方法

复制代码
 public static string GetUrltoHtml(string Url,string type)
        {
            
try
            {
                System.Net.WebRequest wReq 
= System.Net.WebRequest.Create(Url);
                
// Get the response instance.
                System.Net.WebResponse wResp = wReq.GetResponse();
                System.IO.Stream respStream 
= wResp.GetResponseStream();
                
// Dim reader As StreamReader = New StreamReader(respStream)
                using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type)))
                {
                    return reader.ReadToEnd();
                }

            }
            
catch (System.Exception ex)
            {
                
//errorMsg = ex.Message;
            }
            
return "";
        }
复制代码

post方法

复制代码
  ///<summary>
        
///采用https协议访问网络
        
///</summary>
        
///<param name="URL">url地址</param>
        
///<param name="strPostdata">发送的数据</param>
        
///<returns></returns>
        public string OpenReadWithHttps(string URL, string strPostdata, string strEncoding)
        {
            Encoding encoding 
= Encoding.Default;
            HttpWebRequest request 
= (HttpWebRequest)WebRequest.Create(URL);
            request.Method 
= "post";
            request.Accept 
= "text/html, application/xhtml+xml, */*";
            request.ContentType 
= "application/x-www-form-urlencoded";
            
byte[] buffer = encoding.GetBytes(strPostdata);
            request.ContentLength 
= buffer.Length;
            request.GetRequestStream().Write(buffer, 
0, buffer.Length);
            HttpWebResponse response 
= (HttpWebResponse)request.GetResponse();
            using( StreamReader reader 
= new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding(strEncoding)))
              {
                   
return reader.ReadToEnd();
              }
        }
复制代码

 

 阅读全文: http://www.sufeinet.com/thread-6-1-1.html

(评论功能已被禁用)
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示