c# multipart/form-data submit programmatically

前端 未结 4 1227
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-21 06:30

So got an small problem. Im creating an small application to automate an form submission on one website. But the bad thing is that they are using multipart/form-data for tha

相关标签:
4条回答
  • 2020-12-21 07:01

    posts os multipart/form-data type have a different structure because they are meant to transfer data and not just plain text.

    Here's the format:

    --[random number, a GUID is good here]
    Content-Disposition: form-data; name="[name of variable]"
    
    [actual value]
    --[random number, a GUID is good here]--
    

    Using HTTPWebRequest you can create a request that has that format. Here's a sample:

    string boundary = Guid.NewGuid().ToString();
    string header = string.Format("--{0}", boundary);
    string footer = string.Format("--{0}--", boundary);
    
    StringBuilder contents = new StringBuilder();
    contents.AppendLine(header);
    
    contents.AppendLine(header);
    contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "username"));
    contents.AppendLine();
    contents.AppendLine("your_username");
    
    contents.AppendLine(header);
    contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "password"));
    contents.AppendLine();
    contents.AppendLine("your_password");
    
    contents.AppendLine(footer);
    
    0 讨论(0)
  • 2020-12-21 07:14

    The format of multipart/form-data requests is outlined here: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2.

    0 讨论(0)
  • 2020-12-21 07:17

    Here is an article on multipart form posts in C# with more detail. This code was eventually merged into RestSharp, which is an excellent library you could use to generate the request.

    0 讨论(0)
  • 2020-12-21 07:22

    The best way to send multipart form data in C# is shown in the snippet, here you see that adding different type of content is as easy as adding it to the wrapper multipart content type:

    var documentContent = new MultipartFormDataContent();
    documentContent.Add(new StringContent("AnalyticsPage.xlsx"), "title");
    documentContent.Add(new ByteArrayContent(File.ReadAllBytes("C:\\Users\\awasthi\\Downloads\\AnalyticsPage.xlsx")), "file", "AnalyticsPage.xlsx");
    

    Then just make an api call:

    using (var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true, CookieContainer = new CookieContainer() }))
    {
      response = client.PostAsync(documentAddApi, documentContent).Result;
      var responseContent = response.Content.ReadAsStringAsync().Result;
     }
    

    Here the expectation is that the rest endpoint you are making a call to is accepting a 'title' field for the file and the byte array of the file named 'file'.

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