.net MVC_http 批量提交附件,其他参数用文本提交

/// <summary>
    /// 批量提交附件,其他参数用文本提交
    /// </summary>
    /// <param name="Url"></param>
    /// <param name="Files"></param>
    /// <returns></returns>
    public static string UpLoadFileArray_POST(string Url, Dictionary<string, string> Paramters, HttpFileCollection Files)
    {
        string Result = string.Empty;

        string TextHeadStr = "\r\n-----------------------------7df17e3d046e\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";


        string FilesParamsName = "files";
        int Filesindex = 0;
        string FileHeadStr = "\r\n-----------------------------7df17e3d046e\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";

        byte[] HeadByte = new byte[0];
        byte[] EndByte = System.Text.Encoding.UTF8.GetBytes("\r\n-----------------------------7df17e3d046e--\r\n");

        if (Paramters != null)
        {
            foreach (KeyValuePair<string, string> Item in Paramters)
            {
                byte[] PartHead = System.Text.Encoding.UTF8.GetBytes(string.Format(TextHeadStr, Item.Key, Item.Value));
                HeadByte = JoinArray(HeadByte, PartHead);
            }
        }

        if (Files != null)
        {
            for (int i = 0; i < Files.Count; i++)
            {
                HttpPostedFile File = Files[i];
                byte[] PartHead = System.Text.Encoding.UTF8.GetBytes(string.Format(FileHeadStr, FilesParamsName + (++Filesindex), File.FileName));

                byte[] fileContent = null;
                Stream fileStream = File.InputStream;
                int intFileSize = File.ContentLength;
                fileContent = new byte[intFileSize];
                int intStatus = fileStream.Read(fileContent, 0, intFileSize); //文件读取到fileContent数组中
                HeadByte = JoinArray(HeadByte, JoinArray(PartHead, fileContent));
            }

        }

        HeadByte = JoinArray(HeadByte, EndByte);

        Result = UpLoadFile_POST(Url, HeadByte);

        return Result;
    }


/// <summary>
        /// 数据页面请求(POST方式)
        /// </summary>
        /// <param name="p_strUrl">请求地址</param>
        /// <param name="p_strPostData">参数</param>
        /// <param name="p_cContainer">cookie容器</param>
        /// <returns>返回请求结果内容</returns>
        [STAThread]
        public static string PostSubmit(string p_strUrl, string p_strPostData, CookieContainer p_cContainer,string p_strEnctype, Dictionary<string, string> headers)
        {
            
            if (NEEDLOG == "1")
            {
                LogCommon.ilogDebug.Debug("***************************PostSubmit*****************************");
            }
            byte[] data = System.Text.Encoding.UTF8.GetBytes(p_strPostData);

            HttpWebRequest myreq = null;
            // 如果是https网站
            if (p_strUrl.ToLower().Contains("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                myreq = (HttpWebRequest)HttpWebRequest.Create(p_strUrl);
                myreq.ProtocolVersion = HttpVersion.Version10;
                if (NEEDLOG == "1")
                {
                    LogCommon.ilogDebug.Debug("请求为https类型");
                }
            }
            else
            {
                myreq = (HttpWebRequest)HttpWebRequest.Create(p_strUrl);
            }
            myreq.Referer = p_strUrl;
            myreq.Timeout = 1000 * 60 * 10;
            myreq.Method = "POST";
            myreq.KeepAlive = true;
            myreq.AllowAutoRedirect = false;
            myreq.ContentLength = data.Length;
            myreq.CookieContainer = p_cContainer;
            //myreq.ContentType = "multipart/form-data";
            //myreq.ContentType = "application/x-www-form-urlencoded";
            //myreq.ContentType = "application/json";
            myreq.ContentType = p_strEnctype;
            
            myreq.ServicePoint.Expect100Continue = false;
            HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
            myreq.CachePolicy = noCachePolicy;

            if (headers!=null)
            {
                foreach (var key in headers.Keys)
                {
                    string headerValue;
                    headers.TryGetValue(key,out headerValue);
                    myreq.Headers.Add(key, headerValue);
                }
            }

            //如果使用代理
            IWebProxy p = null;
            if (ISPORXY)
            {
                p = new WebProxy(new Uri(PORXYURL));
            }
            myreq.Proxy = p;

            Stream newStream = myreq.GetRequestStream();
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            HttpWebResponse myres = null;
            try
            {
                myres = (HttpWebResponse)myreq.GetResponse();
            }
            catch (Exception ex)
            {
                LogCommon.ilogDebug.Debug("ex=" + ex.Message);
            }
            StreamReader stream;
            Encoding encoding;
            if (!string.IsNullOrEmpty(myres.CharacterSet))
            {
                encoding = Encoding.GetEncoding(myres.CharacterSet);
            }
            else
            {
                encoding = Encoding.Default;
            }
            stream = new StreamReader(myres.GetResponseStream(), encoding);
            string strHtml = stream.ReadToEnd();
            if (myreq != null) myreq.Abort();
            stream.Close();
            myres.Close();
            LogCommon.ilogDebugDb.Debug("strHtml:" + strHtml);
            return strHtml;
        }



/// <summary>
        /// 数据页面请求(重写POST方式)
        /// </summary>
        /// <param name="p_strUrl">请求地址</param>
        /// <param name="data">流数据</param>
        /// <param name="p_strEnctype">内容类型</param>
        /// <param name="p_cContainer">cookie容器</param>
        /// <returns>返回请求结果内容</returns>
        [STAThread]
        public static string PostSubmit(string p_strUrl, byte[] data, string p_strEnctype, CookieContainer p_cContainer, string userid)
        {
            //byte[] data = System.Text.Encoding.ASCII.GetBytes(postData);

            HttpWebRequest myreq = null;

            // 如果是https网站
            if (p_strUrl.ToLower().Contains("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                myreq = (HttpWebRequest)HttpWebRequest.Create(p_strUrl);
                myreq.ProtocolVersion = HttpVersion.Version10;
                if (NEEDLOG == "1")
                {
                    LogCommon.ilogDebug.Debug("请求为https类型");
                }
            }
            else
            {
                myreq = (HttpWebRequest)HttpWebRequest.Create(p_strUrl);
            }
            myreq.Referer = p_strUrl;
            myreq.Method = "POST";
            myreq.Timeout = 1000 * 60 * 10;
            myreq.KeepAlive = true;
            myreq.AllowAutoRedirect = false;
            myreq.ContentLength = data.Length;
            myreq.CookieContainer = p_cContainer;
            //myreq.ContentType = "multipart/form-data";
            //myreq.ContentType = "application/x-www-form-urlencoded";
            myreq.ContentType = p_strEnctype;


            myreq.ServicePoint.Expect100Continue = false;
            HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
            myreq.CachePolicy = noCachePolicy;

            if (!string.IsNullOrEmpty(userid))
            {
                myreq.Headers.Add("userid", userid);
            }

            //如果使用代理
            IWebProxy p = null;
            if (ISPORXY)
            {
                p = new WebProxy(new Uri(PORXYURL));
            }

            myreq.Proxy = p;

            Stream newStream = myreq.GetRequestStream();
            newStream.Write(data, 0, data.Length);

            newStream.Close();

            HttpWebResponse myres = (HttpWebResponse)myreq.GetResponse();
            StreamReader stream;
            Encoding encoding;
            if (!string.IsNullOrEmpty(myres.CharacterSet))
            {
                encoding = Encoding.GetEncoding(myres.CharacterSet);
            }
            else
            {
                encoding = Encoding.Default;
            }
            stream = new StreamReader(myres.GetResponseStream(), encoding);
            string strHtml = stream.ReadToEnd();

            if (myreq != null) myreq.Abort();
            stream.Close();
            myres.Close();
            return strHtml;
        }



        public static string PostAsync(string accountMobile) 
        {
            string sServiceUrl = "https://B2COrg.crm.petrochina:8888/productoilb2c/api/accountmoblie/updata";

            //AccountMobileData model = new AccountMobileData();
            ////model.Name = "20151119123456";
            //model.Id = new Guid("9F4D7ACC-826C-4F70-BF79-1FB44F4FF1FE");
            //model.LeaderTitle = "abc1234";
            //model.CustomerTypeCode = 6;


           // var accountMobile = JsonSerializerHelper.Serializer<AccountMobileData>(model);

            StringContent httpContent = new StringContent(accountMobile, new UTF8Encoding(), "application/json");

            httpContent.Headers.Add("orgname", "b2corg");
            httpContent.Headers.Add("userid", "A45568B8-DB46-E511-80BF-005056AD2DE5");
            HttpClient client = new HttpClient(); 
            var response = client.PostAsync(sServiceUrl, httpContent).Result;
            string result = string.Empty;
            if (response.IsSuccessStatusCode)
            {
                result = response.Content.ReadAsAsync<string>().Result;
            }
            else
            {

                //var errorResult = response.Content.ReadAsAsync<ErrorMessage>().Result;
                //throw new UtilityException(errorResult.Code, errorResult.Message);
                result = "";
            }
            return result;
        }

 

posted @ 2017-11-26 17:37  樊金龙  阅读(54)  评论(0)    收藏  举报