NetworkHelper

19 篇文章 0 订阅
此篇博客介绍了一个名为NetworkHelper的类,用于从给定的URI获取文本,包括处理各种网络请求异常,并支持gzip和deflate编码的解压缩。重点在于处理WebException和SocketException,确保高效稳定的网络数据获取。
摘要由CSDN通过智能技术生成
class NetworkHelper
{
    public static string GetTextFromUri(string uri)
    {
        return GetTextFromUri(uri, Encoding.UTF8);
    }

    public static string GetTextFromUri(string uri, Encoding
    {
        try
        {
            var buffer = GetBytesFromUri(uri);
            return encoding.GetString(buffer);
        }
        catch (Exception)
        {
            return string.Empty;
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="uri"></param>
    /// <returns></returns>
    /// <exception cref="WebException"></exception>
    /// <exception cref="SocketException"></exception>
    public static byte[] GetBytesFromUri(string uri)
        {
            using (WebClient client = new WebClient())
            {
                try
                {
                    client.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36");

                    client.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate"); // 在服务器支持的情况下,接受gzip或deflate压缩流
                    var ns = client.OpenRead(uri);
                    Stream stream = ns;
                    var contentEncoding = client.ResponseHeaders.Get("Content-Encoding");
                    if (contentEncoding == "gzip")
                    {
                        stream = new GZipStream(ns, CompressionMode.Decompress);
                    }
                    else if (contentEncoding == "deflate")
                    {
                        stream = new DeflateStream(ns, CompressionMode.Decompress);
                    }
                    MemoryStream ms = new MemoryStream();
                    stream.CopyTo(ms);
                    return ms.ToArray();
                }
                //通常是404
                catch (System.Net.WebException e)
                {
                    //Logger.Log("Exception at GetXmlFromUri(" + uri + "), msg: " + e.Message);
                    throw;

                }
                //通常是超时
                catch (System.Net.Sockets.SocketException e)
                {
                    //Logger.Log("Exception at GetXmlFromUri(" + uri + "), msg: " + e.Message);
                    throw;
                }

            }
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
namespace ServerDemo { partial class ServerDemo { /// /// 必需的设计器变量。 /// private System.ComponentModel.IContainer components = null; /// /// 清理所有正在使用的资源。 /// /// 如果应释放托管资源,为 true;否则为 false。 protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// /// 设计器支持所需的方法 - 不要 /// 使用代码编辑器修改此方法的内容。 /// private void InitializeComponent() { this.lb_ServerInfo = new System.Windows.Forms.ListBox(); this.bn_Resume = new System.Windows.Forms.Button(); this.bn_Stop = new System.Windows.Forms.Button(); this.bn_Start = new System.Windows.Forms.Button(); this.listBox1 = new System.Windows.Forms.ListBox(); this.cmbClient = new System.Windows.Forms.ComboBox(); this.btnSendto = new System.Windows.Forms.Button(); this.labClientCount = new System.Windows.Forms.Label(); this.SuspendLayout(); // // lb_ServerInfo // this.lb_ServerInfo.FormattingEnabled = true; this.lb_ServerInfo.ItemHeight = 12; this.lb_ServerInfo.Location = new System.Drawing.Point(14, 32); this.lb_ServerInfo.Name = "lb_ServerInfo"; this.lb_ServerInfo.Size = new System.Drawing.Size(572, 100); this.lb_ServerInfo.TabIndex = 61; // // bn_Resume // this.bn_Resume.Location = new System.Drawing.Point(174, 3); this.bn_Resume.Name = "bn_Resume"; this.bn_Resume.Size = new System.Drawing.Size(97, 23); this.bn_Resume.Ta
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值