c#http通讯post表单提交

        /// <summary>
        /// http表单数据上传
        /// </summary>
        /// <param name="uri">地址</param>
        /// <param name="textKeyValue">文本表单数据键值对,key为formName</param>
        /// <param name="fileKeyValue">数据流表单数据键值对,key格式定义:(formName;fileName;MIME)例:dataFile;UploadTest.zip;application/x-zip-compressed</param>
        /// <param name="basicAuthentication">http基本安全验证口令,格式:用户名:密码,默认传空</param>
        /// <returns></returns>
        public static string HttpFormPost(string uri, Dictionary<string, string> textKeyValue = null, Dictionary<string, Stream> fileKeyValue = null, string basicAuthentication = null)
        {
            //定义请求体分割边界
            string _boundary = "ForwardSoft" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
            //定义字节缓存数组
            byte[] _cacheBytes;

            //创建http请求代理工具类
            HttpWebRequest _httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

            #region 定义http请求头
            _httpWebRequest.ContentType = string.Format("multipart/form-data; boundary={0}", _boundary);
            _httpWebRequest.Method = "POST";
            _httpWebRequest.PreAuthenticate = !string.IsNullOrEmpty(basicAuthentication);
            if (_httpWebRequest.PreAuthenticate)
            {
                _cacheBytes = Encoding.UTF8.GetBytes(basicAuthentication);
                string _authenticateBase64 = Convert.ToBase64String(_cacheBytes);
                _httpWebRequest.Headers.Add("Authorization", _authenticateBase64);
            }
            #endregion

            #region 定义http请求体
            //创建http请求体写入流
            var _requestStream = _httpWebRequest.GetRequestStream();

            #region 填充文本表单数据
            if (textKeyValue != null)
            {
                foreach (var _key in textKeyValue.Keys)
                {
                    _cacheBytes = Encoding.UTF8.GetBytes("--" + _boundary);
                    _requestStream.Write(_cacheBytes, 0, _cacheBytes.Length);
                    _requestStream.WriteByte(0x0d);
                    _requestStream.WriteByte(0x0a);
                    _cacheBytes = Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"", _key));
                    _requestStream.Write(_cacheBytes, 0, _cacheBytes.Length);
                    _requestStream.WriteByte(0x0d);
                    _requestStream.WriteByte(0x0a);
                    _requestStream.WriteByte(0x0d);
                    _requestStream.WriteByte(0x0a);
                    _cacheBytes = Encoding.UTF8.GetBytes(textKeyValue[_key]);
                    _requestStream.Write(_cacheBytes, 0, _cacheBytes.Length);
                    _requestStream.WriteByte(0x0d);
                    _requestStream.WriteByte(0x0a);
                }
            }
            #endregion

            #region 填充文件流表单数据
            if (fileKeyValue != null)
            {
                foreach (var _key in fileKeyValue.Keys)
                {
                    var _nameArray = _key.Split(';');
                    _cacheBytes = Encoding.UTF8.GetBytes("--" + _boundary);
                    _requestStream.Write(_cacheBytes, 0, _cacheBytes.Length);
                    _requestStream.WriteByte(0x0d);
                    _requestStream.WriteByte(0x0a);
                    _cacheBytes = Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"", _nameArray[0], _nameArray[1]));
                    _requestStream.Write(_cacheBytes, 0, _cacheBytes.Length);
                    _requestStream.WriteByte(0x0d);
                    _requestStream.WriteByte(0x0a);
                    _cacheBytes = Encoding.UTF8.GetBytes(string.Format("Content-Type: {0}", _nameArray[2]));
                    _requestStream.Write(_cacheBytes, 0, _cacheBytes.Length);
                    _requestStream.WriteByte(0x0d);
                    _requestStream.WriteByte(0x0a);
                    _requestStream.WriteByte(0x0d);
                    _requestStream.WriteByte(0x0a);
                    fileKeyValue[_key].Seek(0, SeekOrigin.Begin);
                    _cacheBytes = new byte[fileKeyValue[_key].Length];
                    fileKeyValue[_key].Read(_cacheBytes, 0, _cacheBytes.Length);
                    _requestStream.Write(_cacheBytes, 0, _cacheBytes.Length);
                    _requestStream.WriteByte(0x0d);
                    _requestStream.WriteByte(0x0a);
                }
            }
            #endregion

            #region 填充结束边界并关闭写入流
            _cacheBytes = Encoding.UTF8.GetBytes("--" + _boundary + "--");
            _requestStream.Write(_cacheBytes, 0, _cacheBytes.Length);
            _requestStream.WriteByte(0x0d);
            _requestStream.WriteByte(0x0a);
            _requestStream.Close();
            #endregion
            #endregion

            string _result;
            //获取服务器端的响应
            using (HttpWebResponse _response = (HttpWebResponse)_httpWebRequest.GetResponse())
            {
                Stream _receiveStream = _response.GetResponseStream();
                StreamReader _readStream = new StreamReader(_receiveStream, Encoding.UTF8);
                _result = _readStream.ReadToEnd();
                _readStream.Close();
                _receiveStream.Close();
            }
            return _result;
        }

PS:对于协议的理解深度完全比使用表层的工具类要重要得多,重要得多,重要得多!

因为一旦你的需求不能通过复制粘贴满足的时候,就必需要自己造轮子。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值