Esempio n. 1
0
        /// <summary>
        /// 执行带文件上传的HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="textParams">请求文本参数</param>
        /// <param name="fileParams">请求文件参数</param>
        /// <returns>HTTP响应</returns>
        public string DoPost(string url, IDictionary <string, string> textParams, IDictionary <string, FileItem> fileParams)
        {
            // 如果没有文件参数,则走普通POST请求
            if (fileParams == null || fileParams.Count == 0)
            {
                return(DoPost(url, textParams));
            }

            string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线

            HttpWebRequest req = GetWebRequest(url, "POST");

            req.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;

            System.IO.Stream reqStream         = req.GetRequestStream();
            byte[]           itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
            byte[]           endBoundaryBytes  = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            // 组装文本请求参数
            string textTemplate = "Content-Disposition:form-data;name=\"{0}\"\r\nContent-Type:text/plain\r\n\r\n{1}";
            IEnumerator <KeyValuePair <string, string> > textEnum = textParams.GetEnumerator();

            while (textEnum.MoveNext())
            {
                string textEntry = string.Format(textTemplate, textEnum.Current.Key, textEnum.Current.Value);
                byte[] itemBytes = Encoding.UTF8.GetBytes(textEntry);
                reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                reqStream.Write(itemBytes, 0, itemBytes.Length);
            }

            // 组装文件请求参数
            string fileTemplate = "Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n";
            IEnumerator <KeyValuePair <string, FileItem> > fileEnum = fileParams.GetEnumerator();

            while (fileEnum.MoveNext())
            {
                string   key      = fileEnum.Current.Key;
                FileItem fileItem = fileEnum.Current.Value;
                if (!fileItem.IsValid())
                {
                    throw new ArgumentException("FileItem is invalid");
                }
                string fileEntry = string.Format(fileTemplate, key, fileItem.GetFileName(), fileItem.GetMimeType());
                byte[] itemBytes = Encoding.UTF8.GetBytes(fileEntry);
                reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                reqStream.Write(itemBytes, 0, itemBytes.Length);
                fileItem.Write(reqStream);
            }

            reqStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            reqStream.Close();

            HttpWebResponse rsp      = (HttpWebResponse)req.GetResponse();
            Encoding        encoding = Encoding.GetEncoding(rsp.CharacterSet);

            return(GetResponseAsString(rsp, encoding));
        }
Esempio n. 2
0
        /// <summary>
        /// 同步POST文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="content"></param>
        /// <param name="fileParams">文件列表</param>
        /// <returns></returns>
        public virtual string Post(string url, object content, IDictionary <string, FileItem> fileParams)
        {
            if (fileParams == null || fileParams.Count == 0)
            {
                return(Post(url, content));
            }

            try
            {
                string result      = null;
                string str_content = this.GetContent(content);

                this.Verify(url, str_content);
                this.SetServicePoint(url);

                using (MultipartFormDataContent httpContent = new MultipartFormDataContent())
                {
                    #region 添加文件

                    IEnumerator <KeyValuePair <string, FileItem> > fileEnum = fileParams.GetEnumerator();
                    while (fileEnum.MoveNext())
                    {
                        string   key      = fileEnum.Current.Key;
                        FileItem fileItem = fileEnum.Current.Value;

                        //StreamContent streamConent = new StreamContent(fileItem.GetStream());
                        //ByteArrayContent imageContent = new ByteArrayContent(streamConent.ReadAsByteArrayAsync().Result);
                        //imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
                        //httpContent.Add(imageContent, key, fileItem.GetFileName());

                        httpContent.Add(new StreamContent(fileItem.GetStream()), key, fileItem.GetFileName());
                    }

                    #endregion 添加文件

                    #region 添加参数

                    if (content is Hashtable)
                    {
                        Hashtable param = content as Hashtable;
                        foreach (string key in param.Keys)
                        {
                            httpContent.Add(new StringContent(param[key].ToString()), key);
                        }
                    }

                    #endregion 添加参数

                    HttpResponseMessage response = this.Client.PostAsync(url, httpContent).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        result = response.Content.ReadAsStringAsync().Result;
                    }
                    else
                    {
                        //LogHelper.Error(string.Format("HttpClientUtils BaseClient PostFile StatusCode:【{0}】,ReasonPhrase:【{1}】", response.StatusCode, response.ReasonPhrase));
                    }

                    httpContent.Dispose();
                }

                return(result);
            }
            catch (System.Threading.ThreadAbortException ex)
            {
                //LogHelper.Error(ex);
                System.Threading.Thread.ResetAbort();
                throw ex;
            }
            catch (HttpRequestException ex)
            {
                //LogHelper.Error(ex);
                throw ex;
            }
            catch (Exception ex)
            {
                //LogHelper.Error(ex.GetType().FullName);
                //LogHelper.Error(ex);
                throw ex;
            }
        }