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

2021-05-14 08:29

阅读:601

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

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

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

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

这里就需要用到HttpClietn类

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

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

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

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

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

请求帮助类:

     /// 
        /// 模拟表单请求/liuyl/2017/09/13
        /// 
        /// 
        /// 
        /// 
        /// 
        public static ErrorCode SendToWebByHttpClient(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) && item.GetValue(value) != null) { foreach (var child in ((List)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(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

上一篇:c#的委托实例

下一篇:c#条件编译符号


评论


亲,登录后才可以留言!