码迷,mamicode.com
首页 > Windows程序 > 详细

通过C#的HttpClient模拟提交form()表单

时间:2017-09-14 21:40:44      阅读:459      评论:0      收藏:0      [点我收藏+]

标签:headers   字符   ext   ndt   集合   inpu   mes   提交   date   

post提交表单一般无非是一般text文本和文件类型,如下

<input type="file"/>
<input type="text"/>

如果模拟post提交表单的过程,该怎么做呢

这里就需要用到HttpClietn类

首先我们需要一个类去包装这些需要上载的数据,例如

   /// <summary>
    /// 包装Data数据的Model
    /// </summary>
    public class SendData
    {
        /// <summary>
        /// 多个文件的
        /// </summary>
        public List<HttpPostedFileBase> FileList { get; set; }

        /// <summary>
        /// 单个文件
        /// </summary>
        public HttpPostedFileBase File{ get; set; }

/// <summary> /// 字节类型 /// </summary> public byte[] ByteBinary { get; set; } /// <summary> /// long类型 /// </summary>public long IconId { get; set; } /// <summary> /// 字符串类型 /// </summary>public string Title { get; set; } /// <summary> /// 时间类型 /// </summary>public DateTime PushTime { get; set; } /// <summary> /// bool类型 /// </summary>public bool PushNow { get; set; } /// <summary> /// long的集合类型 /// </summary> List<long> TestLong { get; set; } = new List<long> { 1, 2, 3, 4, 5, 6 }; /// <summary> /// string的集合类型 /// </summary> List<string> TestString { get; set; } = new List<string> {"1","2","3" }; }

SendToWebByHttpClient("www.....",new SendData{
            FileList =要提交的数据,
            File=要提交的数据,
            ByteBinary=要提交的数据,
              .
              .
              .
              .
              .            })

请求帮助类:

     /// <summary>
        /// 模拟表单请求/liuyl/2017/09/13
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static ErrorCode SendToWebByHttpClient<T>(string url, T value)
        {
            var modelType = typeof(T);
            using (var client = new HttpClient())
            using (var formData = new MultipartFormDataContent())
            {
          //遍历SendData的所有成员
foreach (var item in modelType.GetProperties()) { HttpContent content; //如果是文件类型,在此之前不能进行诸如copy等读取操作,否则在此字节丢失,无法读到字节数据              //文件的处理 if (item.PropertyType == typeof(HttpPostedFileBase) && item.GetValue(value) != null) { #region Stream请求 //Stream塞进Content会导致接受方读取时ContentLength为0,字节丢失 var model = (HttpPostedFileBase)item.GetValue(value); content = new StreamContent(model.InputStream, model.ContentLength); content.Headers.ContentType = MediaTypeHeaderValue.Parse(model.ContentType); content.Headers.ContentLength = model.ContentLength; formData.Add(content, item.Name, model.FileName); #endregion #region 字节方式请求 //var model = (HttpPostedFileBase)item.GetValue(value); //MemoryStream fileTarget = new MemoryStream(); //model.InputStream.CopyTo(fileTarget); //content = new ByteArrayContent(fileTarget.ToArray()); //content.Headers.ContentType = MediaTypeHeaderValue.Parse(model.ContentType); //content.Headers.ContentLength = model.ContentLength; //formData.Add(content, item.Name, model.FileName); #endregion } //文件的处理 else if (item.PropertyType == typeof(HttpPostedFileWrapper) && item.GetValue(value) != null) { #region Stream请求 var model = (HttpPostedFileWrapper)item.GetValue(value); content = new StreamContent(model.InputStream, model.ContentLength); content.Headers.ContentType = MediaTypeHeaderValue.Parse(model.ContentType); content.Headers.ContentLength = model.ContentLength; formData.Add(content, item.Name, model.FileName); #endregion #region 字节方式请求 //var model = (HttpPostedFileWrapper)item.GetValue(value); //MemoryStream fileTarget = new MemoryStream(); //model.InputStream.CopyTo(fileTarget); //content = new ByteArrayContent(fileTarget.ToArray()); //content.Headers.ContentType = MediaTypeHeaderValue.Parse(model.ContentType); //content.Headers.ContentLength = model.ContentLength; //formData.Add(content, item.Name, model.FileName); #endregion } //文件集合的处理 else if (item.PropertyType == typeof(List<HttpPostedFileBase>) && item.GetValue(value) != null) { foreach (var child in ((List<HttpPostedFileBase>)item.GetValue(value))) { #region Stream请求 content = new StreamContent(child.InputStream, child.ContentLength); content.Headers.ContentType = MediaTypeHeaderValue.Parse(child.ContentType); content.Headers.ContentLength = child.ContentLength; formData.Add(content, item.Name, child.FileName); #endregion #region 字节方式请求 //MemoryStream fileTarget = new MemoryStream(); //child.InputStream.CopyTo(fileTarget); //content = new ByteArrayContent(fileTarget.ToArray()); //content.Headers.ContentType = MediaTypeHeaderValue.Parse(child.ContentType); //content.Headers.ContentLength = child.ContentLength; //formData.Add(content, item.Name, child.FileName); #endregion } } //接受字节类型,但是传输传base64格式,否则传byte[],会导致接收方拒绝响应 else if (item.PropertyType == typeof(byte[]) && item.GetValue(value) != null) { content = new StringContent(Convert.ToBase64String((byte[])item.GetValue(value))); formData.Add(content, item.Name); } //其他类型统一按字符串处理 else if (item.GetValue(value) != null && (item.PropertyType != typeof(byte[]) || item.PropertyType != typeof(HttpPostedFileBase))) { content = new StringContent(((string)item.GetValue(value).ToString())); formData.Add(content, item.Name); } } var response = client.PostAsync(url, formData).Result; if (!response.IsSuccessStatusCode) { var obj = JsonHandler.DeserializeObject<BaseViewModel>(response.ToString()); if (obj != null) { var result = obj.ErrResult; if (result.ErrorCode != ErrorCode.OK) { foreach (var message in result.Messages) { _Error += message; } return result.ErrorCode; } } } return ErrorCode.OK; } }

需要特别注意:

如果是上传的文件类型,一定不能在塞入StreamContent数据前对文件进行注入下面操作

HttpPostedFileBase file = item;//你的文件
                PictureListType pictureListType = new PictureListType();
                MemoryStream target = new MemoryStream();
                file.InputStream.CopyTo(target);//进行此操作后,在之后发起请求时读此文件流会失败,ContentLength=0
                pictureListType.PictureBinary = target.ToArray();

 

通过C#的HttpClient模拟提交form()表单

标签:headers   字符   ext   ndt   集合   inpu   mes   提交   date   

原文地址:http://www.cnblogs.com/xiaoliangge/p/7522828.html

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