码迷,mamicode.com
首页 > Web开发 > 详细

http方式获取远程文件内容

时间:2019-07-03 13:35:43      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:throw   str   stream   encoding   pat   https   col   文件   nal   

 

    public class HttpServer
    {
        /// <summary>
        /// 读取远程文件的内容
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public string ReadFromFile(string serverFilePath)
        {
            if (string.IsNullOrEmpty(serverFilePath))
                return "";

            string ret = "";
            HttpWebRequest req = null;
            HttpWebResponse resp = null;

            try
            {
                req = (HttpWebRequest)HttpWebRequest.Create(serverFilePath);
                req.Method = "GET";
                req.KeepAlive = false;

                resp = req.GetResponse() as HttpWebResponse;
                using (Stream stream = resp.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        ret = reader.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (req != null)
                    req.Abort();
                if (resp != null)
                    resp.Close();
            }

            return ret;
        }

        /// <summary>
        /// 读取远程文件的内容(异步)
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public async Task<string> ReadFromFileAsync(string serverFilePath)
        {
            if (string.IsNullOrEmpty(serverFilePath))
                return "";

            string ret = "";
            HttpWebRequest req = null;
            HttpWebResponse resp = null;

            try
            {
                req = (HttpWebRequest)HttpWebRequest.Create(serverFilePath);
                req.Method = "GET";
                req.KeepAlive = false;

                resp = req.GetResponse() as HttpWebResponse;
                using (Stream stream = resp.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        ret = await reader.ReadToEndAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (req != null)
                    req.Abort();
                if (resp != null)
                    resp.Close();
            }

            return ret;
        }
    }

 

http方式获取远程文件内容

标签:throw   str   stream   encoding   pat   https   col   文件   nal   

原文地址:https://www.cnblogs.com/yaosj/p/11125565.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!