C#.net模拟提交表单POST

本文介绍了如何在.NETFramework3.5中使用System.Net.WebClient类进行HTTPPOST请求,以及如何实现更高级别的MultipartFormData上传,包括文件和键值对数据。
摘要由CSDN通过智能技术生成

framework3.5以上

System.Net.WebClient WebClientObj        = new System.Net.WebClient();
   System.Collections.Specialized.NameValueCollection PostVars  = new System.Collections.Specialized.NameValueCollection();
   PostVars.Add("A1","1");
   PostVars.Add("A2","2");
   PostVars.Add("A3","3");

   try
   {
    byte[] byRemoteInfo   = WebClientObj.UploadValues("http://xxx/xx","POST",PostVars);
    string result= System.Text.Encoding.Default.GetString(byRemoteInfo);  
   }
   catch
   {

   }

framework3.5

        public static string UploadMultipartFormData(string url, string httpMethod, Dictionary<string, string> headers, NameValueCollection nameValueCollection, NameValueCollection fileCollection)
        {
            var boundary = string.Format("batch_{0}", Guid.NewGuid());
            var startBoundary = string.Format("--{0}", boundary);

            // Set up Request body.
            WebRequest request = HttpWebRequest.Create(url);
            foreach (var item in headers)
            {
                request.Headers.Add(item.Key, item.Value);
            }
            request.Method = httpMethod;

            request.ContentType = "multipart/form-data; boundary=" + boundary;

            // Writes the boundary and Content-Disposition header, then writes
            // the file binary, and finishes by writing the closing boundary.
            using (Stream requestStream = request.GetRequestStream())
            {
                StreamWriter writer = new StreamWriter(requestStream);

                // 处理文件内容
                string[] fileKeys = fileCollection.AllKeys;
                foreach (string key in fileKeys)
                {
                    WriteFileToStream(writer, startBoundary, key, fileCollection[key]);
                }

                // 键值对参数
                string[] allKeys = nameValueCollection.AllKeys;
                foreach (string key in allKeys)
                {
                    WriteNvToStream(writer, startBoundary, key, nameValueCollection[key]);
                }

                var endFormData = CRLF + string.Format("--{0}--", boundary) + CRLF;

                writer.Write(endFormData);
                writer.Flush();
                writer.Close();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string json = new StreamReader(response.GetResponseStream()).ReadToEnd();

            return json;
        }

        static void WriteFileToStream(StreamWriter writer, string startBoundary, string name, string filePath)
        {
            var filename = Path.GetFileName(filePath);
            var fileRequestBody = startBoundary + CRLF;
            fileRequestBody += "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + filename + "\"" + CRLF + CRLF;

            writer.Write(fileRequestBody);
            writer.Flush();

            byte[] bmpBytes = File.ReadAllBytes(filePath);
            writer.BaseStream.Write(bmpBytes, 0, bmpBytes.Length);
        }

        static void WriteNvToStream(StreamWriter writer, string startBoundary, string name, string value)
        {
            var nvFormData = CRLF + startBoundary + CRLF;
            nvFormData += "Content-Disposition: form-data; name=\"" + name + "\"" + CRLF + CRLF;
            nvFormData += value /*+ CRLF*/;

            writer.Write(nvFormData);
            writer.Flush();
        }

  • 13
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值