C# HttpWebRequest post 数据与上传图片到server

主体

            Dictionary<string, object> postData = new Dictionary<string, object>();           
            string fileFullPath = this.imgFullPath;
            if (!File.Exists(fileFullPath))
            {
                Message(Error, "file not exist: " + fileFullPath);
                goto EndGetPost;
            }

            // 先定义一个byte数组
            // 将指定的文件数据读取到 数组中
            byte[] bFile = null;

            // path是文件的路径
            using (FileStream fs = new FileStream(fileFullPath, FileMode.Open))
            {
                // 定义这个byte[]数组的长度 为文件的length
                bFile = new byte[fs.Length];

                // 把fs文件读入到arrFile数组中,0是指偏移量,从0开始读,arrFile.length是指需要读的长度,也就是整个文件的长度
                fs.Read(bFile, 0, bFile.Length);
            }

            postData.Add("file", new FileParameter(bFile, fileFullPath, "image/jpg"));


//--------------------------------------

// Create request and receive response
                string postURL = this.url;
               
                string userAgent = "Mozilla/5.0 (Windows NT 10.0;Win64;x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
                HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL, userAgent, postParameters);

                // Process response
                StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
                fullResponse = responseReader.ReadToEnd();
                responseReader.Close();
                webResponse.Close();

 /// <summary>
    /// 表单数据项.
    /// </summary>
    public static class FormUpload
    {
        private static readonly Encoding ENCODING = Encoding.UTF8;

        /// <summary>
        /// MultipartFormDataPost.
        /// </summary>
        /// <param name="postUrl">.</param>
        /// <param name="userAgent">string.</param>
        /// <param name="postParameters">send.</param>
        /// <returns>HttpWebResponse.</returns>
        public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string, object> postParameters)
        {
            string formDataBoundary = string.Format("----------{0:N}", Guid.NewGuid());
            string contentType = "multipart/form-data; boundary=" + formDataBoundary;
            byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);

            return PostForm(postUrl, userAgent, contentType, formData);
        }

        /// <summary>
        /// send to api.
        /// </summary>
        /// <param name="postUrl">url.</param>
        /// <param name="userAgent">string agent.</param>
        /// <param name="contentType">send type.</param>
        /// <param name="formData">type.</param>
        /// <returns>HttpWebResponse.</returns>
        private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData)
        {
            // use https or http
            // HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
            HttpWebRequest request = null;
            if (postUrl.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                Message(Warning, "use https:-------");
                request = WebRequest.Create(postUrl) as HttpWebRequest;
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request.ProtocolVersion = HttpVersion.Version11;

                // 这里设置了协议类型。
                // SecurityProtocolType.Tls1.2;
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                request.KeepAlive = false;
                ServicePointManager.CheckCertificateRevocationList = true;
                ServicePointManager.DefaultConnectionLimit = 100;
                ServicePointManager.Expect100Continue = false;
            }
            else
            {
                Message(Warning, "use http default");
                request = (HttpWebRequest)WebRequest.Create(postUrl);
            }

            // start -------
            if (request == null)
            {
                throw new NullReferenceException("request is not a http request");
            }

            // Set up the request properties.
            request.Method = "POST";
            request.ContentType = contentType;
            request.UserAgent = userAgent;
            request.CookieContainer = new CookieContainer();
            request.ContentLength = formData.Length;
            request.Accept = "application/json";


            // You could add authentication here as well if needed:
            // request.PreAuthenticate = true;
            // request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
            // request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("username" + ":" + "password")));

            // Send the form data to the request.
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(formData, 0, formData.Length);
                requestStream.Close();
            }

            return request.GetResponse() as HttpWebResponse;
        }

        private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
        {
            Stream formDataStream = new System.IO.MemoryStream();
            bool needsCLRF = false;

            foreach (var param in postParameters)
            {
                // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
                // Skip it on the first parameter, add it to subsequent parameters.
                if (needsCLRF)
                {
                    formDataStream.Write(ENCODING.GetBytes("\r\n"), 0, ENCODING.GetByteCount("\r\n"));
                }

                needsCLRF = true;

                if (param.Value is FileParameter)
                {
                    FileParameter fileToUpload = (FileParameter)param.Value;

                    // Add just the first part of this param, since we will write the file data directly to the Stream
                    string header = string.Format(
                        "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
                        boundary,
                        param.Key,
                        fileToUpload.FileName ?? param.Key,
                        fileToUpload.ContentType ?? "application/octet-stream");

                    formDataStream.Write(ENCODING.GetBytes(header), 0, ENCODING.GetByteCount(header));

                    // Write the file data directly to the Stream, rather than serializing it to a string.
                    formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);
                }
                else
                {
                    string postData = string.Format(
                        "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
                        boundary,
                        param.Key,
                        param.Value);
                    formDataStream.Write(ENCODING.GetBytes(postData), 0, ENCODING.GetByteCount(postData));
                }
            }

            // Add the end of the request.  Start with a newline
            string footer = "\r\n--" + boundary + "--\r\n";
            formDataStream.Write(ENCODING.GetBytes(footer), 0, ENCODING.GetByteCount(footer));

            // Dump the Stream into a byte[]
            formDataStream.Position = 0;
            byte[] formData = new byte[formDataStream.Length];
            formDataStream.Read(formData, 0, formData.Length);
            formDataStream.Close();

            return formData;
        }

        /// <summary>
        /// CheckValidationResult.
        /// </summary>
        /// <param name="sender">sender.</param>
        /// <param name="certificate">certificate.</param>
        /// <param name="chain">chain.</param>
        /// <param name="errors">errors.</param>
        /// <returns>true.</returns>
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            // 总是接受
            return true;
        }
    }


 /// <summary>
    /// FileParameter.
    /// </summary>
    public class FileParameter
    {

        /// <summary>
        /// Initializes a new instance of the <see cref="FileParameter"/> class.
        /// FileParameter.
        /// </summary>
        /// <param name="file">file.</param>
        /// <param name="filename">filename.</param>
        /// <param name="contenttype">contenttype.</param>
        public FileParameter(byte[] file, string filename, string contenttype)
        {
            this.File = file;
            this.FileName = filename;
            this.ContentType = contenttype;
        }

        /// <summary>
        /// Gets or sets File.
        /// </summary>
        public byte[] File { get; set; }

        /// <summary>
        /// Gets or sets FileName.
        /// </summary>
        public string FileName { get; set; }

        /// <summary>
        /// Gets or sets ContentType.
        /// </summary>
        public string ContentType { get; set; }
    }


 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 `HttpWebRequest` 类来发送带有 `form-data` 的 POST 请求。 以下是一个示例代码: ```csharp public static string HttpPostForm(string url, Dictionary<string, object> formData, string boundary) { string result = string.Empty; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "multipart/form-data; boundary=" + boundary; using (Stream requestStream = request.GetRequestStream()) { // 添加表单数据 foreach (var item in formData) { if (item.Value is byte[]) { byte[] fileData = (byte[])item.Value; string fileName = item.Key; string fileContentType = "application/octet-stream"; // 写入文件数据 WriteFileData(requestStream, boundary, fileName, fileContentType, fileData); } else { // 写入表单数据 WriteFormData(requestStream, boundary, item.Key, item.Value.ToString()); } } // 写入结束标识 WriteEndBoundary(requestStream, boundary); } // 发送请求 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8)) { result = reader.ReadToEnd(); } } } return result; } private static void WriteFormData(Stream stream, string boundary, string key, string value) { string formDataTemplate = "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n"; string formData = string.Format(formDataTemplate, boundary, key, value); byte[] formDataBytes = Encoding.UTF8.GetBytes(formData); stream.Write(formDataBytes, 0, formDataBytes.Length); } private static void WriteFileData(Stream stream, string boundary, string fileName, string fileContentType, byte[] fileData) { string fileDataTemplate = "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n"; string fileDataHeader = string.Format(fileDataTemplate, boundary, "file", fileName, fileContentType); byte[] fileDataHeaderBytes = Encoding.UTF8.GetBytes(fileDataHeader); stream.Write(fileDataHeaderBytes, 0, fileDataHeaderBytes.Length); stream.Write(fileData, 0, fileData.Length); byte[] fileDataEndBytes = Encoding.UTF8.GetBytes("\r\n"); stream.Write(fileDataEndBytes, 0, fileDataEndBytes.Length); } private static void WriteEndBoundary(Stream stream, string boundary) { string endBoundaryTemplate = "--{0}--\r\n"; string endBoundary = string.Format(endBoundaryTemplate, boundary); byte[] endBoundaryBytes = Encoding.UTF8.GetBytes(endBoundary); stream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); } ``` 其中,`HttpPostForm` 方法用于发送 POST 请求,接收一个 url、一个表单数据字典、一个边界字符串作为参数。在方法内部,我们首先设置请求方法和请求头,然后通过 `GetRequestStream` 方法获取请求流。在请求流中,我们遍历表单数据字典,将表单数据和文件数据分别写入请求流中,最后写入结束标识。最后,我们通过 `GetResponse` 方法获取响应,并将响应内容读取出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值