.net通过接口获取二进制文件存储到本地并下载


using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.IO;
    public void show(string id, string type, string zzkkk)
    {
        string api = "4562C3D1D1A6492293BB18A98D451990";
        string pageNumber = "2";
        string pageSize = "20";
        string a200 = "现行,未生效";
        //string a826 = "35.100.01";
        //string a826 = this.Aid.Text;\
        string a826 = "402881b447703d8e01489bd3ba0b5044";
        string signkey = "6420200A52424133894FCD9897B1DA0B";
        string api1 = "http://123.232.123.17:9090/services/stdquery/querydown";
        //string api1 = "http://123.232.123.17:9090/services/stdbuy/purchase";
        //string api1 = "http://123.232.123.17:9090/services/stdbuy/downorderfile";
        SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();

        //sParaTemp.Add("pageNumber", pageNumber);
        //sParaTemp.Add("pageSize", pageSize);
        //sParaTemp.Add("a200", a200);
        //sParaTemp.Add("a826", a826);
        sParaTemp.Add("id", id);

        //得到序列化的参数值  
        string data = ceShi.Until.datapost(sParaTemp);
        string dataa = data + signkey;

        //string sign = byte2String;
        string sign = GetMd5Str(dataa);
        SortedDictionary<string, string> sParaTemp1 = new SortedDictionary<string, string>();
        sParaTemp1.Add("api", api);
        sParaTemp1.Add("sign", sign);
        sParaTemp1.Add("id", id);//402881b447703d8e01489bd3ba0b5044

        string data1 = ceShi.Until.datapost1(sParaTemp1);
        string time = DateTime.Now.ToString("yyyyMMddHHmmssfff");
        string src = "UpBZ/PDF/" + zzkkk + "ss" + time + ".pdf";
        if (!Directory.Exists(HttpContext.Current.Request.PhysicalApplicationPath + "UpBZ/PDF/" + zzkkk))
        {
            Directory.CreateDirectory(HttpContext.Current.Request.PhysicalApplicationPath + "UpBZ/PDF/" + zzkkk);
        }
        modelpdf.bzid = id;
        modelpdf.name = time + id;
        modelpdf.dizhi = "/" + src;
        modelpdf.state = "0";
        int zzh = 0;
        //int zzh = bllpdf.Add(modelpdf);
        //进行post提交  
        string result = ceShi.Until.Post(data1, api1, 666, id, HttpContext.Current.Request.PhysicalApplicationPath + src);
        if (result != "无附件")
        {
            if (result == "000")
            {
                DataSet dds = bllpdf.GetList(" bzid='" + id + "'");
                if (dds.Tables[0].Rows.Count > 0)
                {
                    modelpdf = bllpdf.GetModel(Convert.ToInt32(dds.Tables[0].Rows[0]["id"]));
                    modelpdf.state = "1";
                    bllpdf.Update(modelpdf);
                    if (type == "xz")
                    {
                        //xzpdf(id, "");
                    }
                    else if (type == "yl")
                    {
                        ylpdf(id);
                    }
                }
            }
            else
            {
                //bllpdf.Delete(zzh);
                ScriptManager.RegisterStartupScript(Page, typeof(Page), "tishi", "alert('该项没有附件!');", true);
            }
        }
        else
        {
            //bllpdf.Delete(zzh);
            ScriptManager.RegisterStartupScript(Page, typeof(Page), "tishi", "alert('该项没有附件!');", true);
        }

        //Response.Write(result);
    }

Util.cs

using System;  
using System.Collections.Generic;  
using System.Web;  
using System.Net;  
using System.IO;  
using System.Text;  
using System.Net.Security;  
using System.Security.Authentication;  
using System.Security.Cryptography.X509Certificates;

namespace ceShi
{
    public class Until : System.Web.UI.UserControl
    {
        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)  
        {  
            //直接确认,否则打不开      
            return true;  
        }  
  
  
        /// <summary>  
        /// 得到需要传递的参数格式  
        /// </summary>  
        /// <param name="sParaTemp">参数键值</param>  
        /// <returns></returns>  
        public static string datapost(SortedDictionary<string, string> sParaTemp)  
        {  
            Encoding myEncoding = Encoding.GetEncoding("utf-8");    
            StringBuilder prestr = new StringBuilder();  
            foreach (KeyValuePair<string, string> temp in sParaTemp)  
            {  
                prestr.Append(temp.Key + "=" + temp.Value + "");  
            }  
  
  
            return prestr.ToString();  
        }
        /// <summary>  
        /// 得到需要传递的参数格式  
        /// </summary>  
        /// <param name="sParaTemp">参数键值</param>  
        /// <returns></returns>  
        public static string datapost1(SortedDictionary<string, string> sParaTemp)
        {
            Encoding myEncoding = Encoding.GetEncoding("utf-8");
            StringBuilder prestr = new StringBuilder();
            prestr.Append("{");
            foreach (KeyValuePair<string, string> temp in sParaTemp)
            {
                prestr.Append("\"" + temp.Key + "\":\"" + temp.Value + "\",");
            }
            string ss = prestr.ToString();
            ss = ss.Substring(0, ss.Length - 1);//去掉最后一个逗号
            ss=ss + "}";
            return ss;
        }  
  
  
        /// <summary>  
        /// post方式提交  
        /// </summary>  
        /// <param name="postdata">传递的参数先调用datapost()方法</param>  
        /// <param name="url">访问的地址</param>  
        /// <param name="timeout">超时时间 6</param>  
        /// <returns></returns>  
        public static string Post(string postdata, string url, int timeout,string id,string src)  
        {  
            
            //ceShi.NetFramework.Helper.LogHelper.LogSave(string.Format("postdata: {0} url: {1} timeout:{2}", postdata, url, timeout));  
            System.GC.Collect();//垃圾回收,回收没有正常关闭的http连接  

            string Err = "";//返回的错误信息
            string result = "";//返回结果    
  
            HttpWebRequest request = null;  
            HttpWebResponse response = null;
            HttpWebResponse hres = null;
            Stream reqStream = null;  
    


            try  
            {  
                //设置最大连接数  
                ServicePointManager.DefaultConnectionLimit = 200;  
                //设置https验证方式  
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))  
                {  
                    ServicePointManager.ServerCertificateValidationCallback =  
                            new RemoteCertificateValidationCallback(CheckValidationResult);  
                }  
    
                /*************************************************************** 
                * 下面设置HttpWebRequest的相关属性 
                * ************************************************************/  
                request = (HttpWebRequest)WebRequest.Create(url);  
    
                request.Method = "POST";  
                request.Timeout = timeout * 10000;  
    
                //这个在Post的时候,一定要加上,如果服务器返回错误,他还会继续再去请求,不会使用之前的错误数据,做返回数据  
                request.ServicePoint.Expect100Continue = false;  
   
                //设置代理服务器  
                //WebProxy proxy = new WebProxy();                          //定义一个网关对象  
                //proxy.Address = new Uri(WxPayConfig.PROXY_URL);              //网关服务器端口:端口  
                //request.Proxy = proxy;  
    
                //设置POST的数据类型和长度  
                request.ContentType = "application/json;charset=utf-8";  
                byte[] data = System.Text.Encoding.UTF8.GetBytes(postdata);  
                request.ContentLength = data.Length;  
    
                是否使用证书  
                //if (isUseCert)  
                //{  
                //    string path = HttpContext.Current.Request.PhysicalApplicationPath;  
                //    X509Certificate2 cert = new X509Certificate2(path + WxPayConfig.SSLCERT_PATH, WxPayConfig.SSLCERT_PASSWORD);  
                //    request.ClientCertificates.Add(cert);  
                //    //Log.Debug("WxPayApi", "PostXml used cert");  
                //}    
  
                //往服务器写入数据  
                reqStream = request.GetRequestStream();  
                reqStream.Write(data, 0, data.Length);  
                reqStream.Close();  
   
                //获取服务端返回  
                response = (HttpWebResponse)request.GetResponse();
                string savePath = src;
                string ss = "001";
                //获取服务端返回数据  
                //string zzss = response.ContentType.ToLower();
                hres = response;
                //if (response.ContentType.ToLower().Contains("pdf"))
                if (1 == 1)
                {
                    using (Stream reader = response.GetResponseStream())
                    {
                        //long ssa = reader.Length;
                        string ass = reader.ToString();
                        using (FileStream writer = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            byte[] sss = new byte[1024];
                            byte[] buffer = new byte[1024];
                            int si = buffer.Length;
                            int c = 0;
                                while ((c = reader.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    writer.Write(buffer, 0, c);
                                    if(c==1024){
                                    ss = "000";
                                    }
                                }
                            writer.Close();
                        }
                    }
                }

                //StreamReader sOut = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                //result = sOut.ReadToEnd();
                result = ss;
            }  
            catch (System.Threading.ThreadAbortException e)  
            {
                Err += e.ToString();
                return "无附件";
                //string.Format("Exception message: {0}", e.Message);
                //Log.Error("HttpService", "Thread - caught ThreadAbortException - resetting.");  
                //Dvmt.NetFramework.Helper.LogHelper.LogSave(string.Format("Exception message: {0}", e.Message));  
                //System.Threading.Thread.ResetAbort();  
            }  
            catch (WebException e)  
            {               
                //fdx
                Err += e.ToString();
                return "无附件";
                //string.Format("Exception message: {0}", e.Message);
                //Log.Error("HttpService", e.ToString());  
                //if (e.Status == WebExceptionStatus.ProtocolError)  
                //{  
                    //Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);  
                    //Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);  
                //}  
                //throw new WxPayException(e.ToString());  
                //Dvmt.NetFramework.Helper.LogHelper.LogSave(string.Format("WebException message: {0}", e.Message));  
            }  
            catch (Exception e)
            {
                Err += e.ToString();
                return "无附件";
                //string.Format("Exception message: {0}", e.Message);
                //Dvmt.NetFramework.Helper.LogHelper.LogSave(string.Format("Exception message: {0}", e.Message));  
                //Log.Error("HttpService", e.ToString());  
                //throw new WxPayException(e.ToString());  
            }  
            finally  
            {  
                //关闭连接和流  
                if (response != null)  
                {  
                    response.Close();  
                }  
                if (request != null)  
                {  
                    request.Abort();  
                }  
            }
            while (true)
            {
                if (result != null && result.Trim() != "")
                {
                    return result;
                }
                else
                {
                    return Err;
                }
            }
           
            
        }  
    
        / <summary>  
        / 处理http GET请求,返回数据  
        / </summary>  
        / <param name="url">请求的url地址</param>  
        / <returns>http GET成功后返回的数据,失败抛WebException异常</returns>  
        //public static string Get(string url)  
        //{  
        //    System.GC.Collect();  
        //    string result = "";  
    
        //    HttpWebRequest request = null;  
        //    HttpWebResponse response = null;  
    
        //    //请求url以获取数据  
        //    try  
        //    {  
        //        //设置最大连接数  
        //        ServicePointManager.DefaultConnectionLimit = 200;  
        //        //设置https验证方式  
        //        if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))  
        //        {  
        //            ServicePointManager.ServerCertificateValidationCallback =  
        //                    new RemoteCertificateValidationCallback(CheckValidationResult);  
        //        }  
    
        //        /*************************************************************** 
        //        * 下面设置HttpWebRequest的相关属性 
        //        * ************************************************************/  
        //        request = (HttpWebRequest)WebRequest.Create(url);  
    
        //        request.Method = "GET";  
   
        //        //设置代理  
        //        //WebProxy proxy = new WebProxy();  
        //        //proxy.Address = new Uri(WxPayConfig.PROXY_URL);  
        //        //request.Proxy = proxy;  
  
  
        //        //获取服务器返回  
        //        response = (HttpWebResponse)request.GetResponse();  
    
        //        //获取HTTP返回数据  
        //        StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);  
        //        result = sr.ReadToEnd().Trim();  
        //        sr.Close();  
        //    }  
        //    catch (System.Threading.ThreadAbortException e)
        //    {
        //        //Log.Error("HttpService", "Thread - caught ThreadAbortException - resetting.");  
        //        //Log.Error("Exception message: {0}", e.Message);  
        //        System.Threading.Thread.ResetAbort();  
        //    }  
        //    catch (WebException e)  
        //    {  
        //        //Log.Error("HttpService", e.ToString());  
        //        //if (e.Status == WebExceptionStatus.ProtocolError)  
        //        //{  
        //        //    Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);  
        //        //    Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);  
        //        //}  
        //        //throw new WxPayException(e.ToString());  
        //    }  
        //    catch (Exception e)  
        //    {  
        //        //Log.Error("HttpService", e.ToString());  
        //        //throw new WxPayException(e.ToString());  
        //    }  
        //    finally  
        //    {  
        //        //关闭连接和流  
        //        if (response != null)  
        //        {  
        //            response.Close();  
        //        }  
        //        if (request != null)  
        //        {  
        //            request.Abort();  
        //        }  
        //    }  
        //    return result;  
        //}
      
    }  
} 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值