HttpClient setting boundary with content-type

后端 未结 3 813
野的像风
野的像风 2021-01-13 02:09

I am using javascript to communicate with a third party service. As part of their authentication process they need the \"multipart/form\" body of the post message including

相关标签:
3条回答
  • 2021-01-13 02:42

    I post my code here, maybe this will help anyone else struggling as I did, on my case this works and upload a file to my account (not a banking but a secure cloud file product)

     public  string UploadFile(string endpointUrl, string filePath, string accessToken)
        {
    
            FileStream fs = null;
            Stream rs = null;
            string result = "";
            try
            {
    
                string uploadFileName = System.IO.Path.GetFileName(filePath);
    
                fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
    
                var request = (HttpWebRequest)WebRequest.Create(endpointUrl);
                request.Method = WebRequestMethods.Http.Post;
                request.AllowWriteStreamBuffering = false;
                request.SendChunked = true;
                String CRLF = "\r\n"; // Line separator required by multipart/form-data.        
                long timestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
    
                string boundary = timestamp.ToString("x");
                request.ContentType = "multipart/form-data; boundary=" + boundary;
    
                request.Headers.Add("Authorization", "Bearer " + accessToken);                             
    
                long bytesAvailable = fs.Length;
                long maxBufferSize = 1 * 1024 * 1024;
    
    
                rs = request.GetRequestStream();
                byte[] buffer = new byte[50];
                int read = 0;
    
                byte[] buf = Encoding.UTF8.GetBytes("--" + boundary + CRLF);
                rs.Write(buf, 0, buf.Length);
    
                buf = Encoding.UTF8.GetBytes("Content-Disposition: form-data; name=\"body\"; filename=\"" + uploadFileName + "\"" + CRLF);                
                rs.Write(buf, 0,buf.Length);
    
                buf = Encoding.UTF8.GetBytes("Content-Type: application/octet-stream;" + CRLF);
                rs.Write(buf, 0, buf.Length);
    
                buf = Encoding.UTF8.GetBytes(CRLF);
                //writer.append("Content-Type: application/octet-stream;").append(CRLF);
                rs.Write(buf, 0, buf.Length);
                rs.Flush();
    
    
                long bufferSize = Math.Min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                while ((read = fs.Read(buffer, 0, buffer.Length)) != 0)
                {
                    rs.Write(buffer, 0, read);
                }
                buf = Encoding.UTF8.GetBytes(CRLF);                
                rs.Write(buf, 0, buf.Length);
                rs.Flush();
    
    
                // End of multipart/form-data.
                buffer = Encoding.UTF8.GetBytes("--" + boundary + "--" + CRLF);
                rs.Write(buffer, 0, buffer.Length);
    
                using (var response = request.GetResponse())
                using (var responseStream = response.GetResponseStream())
                using (var reader = new StreamReader(responseStream))
                {
    
                    result = reader.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                result = e.InnerException != null ? e.InnerException.Message : e.Message;  
            }
    
            return result;
        }
    
    0 讨论(0)
  • 2021-01-13 02:52

    with HttpClient

     request.Content.Headers.Add("ContentType", "multipart/form-data, boundary=------------ThIs_Is_tHe_bouNdaRY_");
    

    you can use HttpWebRequest

     myHttpWebRequest.Date = DateTime.Now;
     myHttpWebRequest.ContentType = "multipart/form-data, boundary=------------ThIs_Is_tHe_bouNdaRY_";
    
    0 讨论(0)
  • 2021-01-13 03:05

    We solved this by manually clearing and re-adding the content type without validation it seems that the MediaTypeHeaderValue() class doesn't like the boundary tags.

    instead of using :

    content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data; boundary=----FLICKR_MIME_20140415120129--");
    

    we did the following:

    content.Headers.Remove("Content-Type");
    content.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=----FLICKR_MIME_20140415120129--");
    

    Once we made this change it all worked correctly.

    (Note that this is on WinRT if that makes any difference)

    0 讨论(0)
提交回复
热议问题