c#文件下载示例的4种方法

C#实现HTTP下载文件的方法

/// <summary>
        /// Http下载文件
        /// </summary>
        public static string HttpDownloadFile(string url, string path, object t)
        {
            string strJson = JsonConvert.SerializeObject(
                    t,
                    Formatting.Indented,
                    new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
            string strURL = url;
            //创建一个HTTP请求  
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
            //Post请求方式  
            request.Method = "POST";
            //内容类型
            request.ContentType = "application/json";

            //设置参数,并进行URL编码 

            string paraUrlCoded = strJson;//System.Web.HttpUtility.UrlEncode(jsonParas);   

            byte[] payload;
            //将Json字符串转化为字节  
            payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
            //设置请求的ContentLength   
            request.ContentLength = payload.Length;
            //发送请求,获得请求流 

            Stream writer;
            try
            {
                writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
            }
            catch (Exception)
            {
                writer = null;
                // return "连接服务器失败!";
                throw new Exception("连接服务器失败!");
            }
            //将请求参数写入流
            writer.Write(payload, 0, payload.Length);
            writer.Close();//关闭请求流
            // String strValue = "";//strValue为http响应所返回的字符流
            HttpWebResponse response;
            try
            {
                //获得响应流
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                if ("远程服务器返回错误: (400) 错误的请求。".Equals(ex.Message))
                {
                    throw new Exception("远程服务器返回错误: (400) 错误的请求。传参错误!");
                }
                response = ex.Response as HttpWebResponse;
                throw new Exception("服务器响应失败!");
            }
            if (response == null)
            {
                throw new Exception("连接服务器失败!");
            }
            Stream responseStream = response.GetResponseStream();
            //创建本地文件写入流
            Stream stream = new FileStream(path, FileMode.Create);
            byte[] bArr = new byte[1024];
            int size = responseStream.Read(bArr, 0, (int)bArr.Length);
            while (size > 0)
            {
                stream.Write(bArr, 0, size);
                size = responseStream.Read(bArr, 0, (int)bArr.Length);
            }
            stream.Close();
            responseStream.Close();
            return path;
        }

 

上一篇:拒绝Writer以.NET的名义,抄书抄博客贩卖焦虑,收割粉丝经济,毒害社区!


下一篇:android日志打印