Jayoti Parkash
Jayoti Parkash

Reputation: 878

How to make a post request with body option form-data

Would anyone know how to convert the below Postman POST Body form-data parameters to C# POST request, I tried a lot using HttpClient, Web request at my end but it's not working.

enter image description here

Sample code:

var bytes = (dynamic)null;
using (HttpClient httpClient = new HttpClient())
 {
    using (var multiPartContent = new MultipartFormDataContent())
    {
        var fileContent = new ByteArrayContent(documentData);
    
        //Add file to the multipart request
        multiPartContent.Headers.Add("format_source", FORMAT_SOURCE);
        multiPartContent.Headers.Add("format_target", FORMAT_TARGET);
        multiPartContent.Add(fileContent);
    
        //Post it
        bytes = httpClient.PostAsync(CONVERSION_URL, multiPartContent).Result;
    }
}

Postman code: C# RestSharp:

var client = new RestClient("http://test-service-staging.test.com/convert");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddFile("input", "/C:/Users/DR-11/Downloads/response_1592912235925.xml");
request.AddParameter("format_source", "abc");
request.AddParameter("format_target", "xyz");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

HTTP:

POST /convert HTTP/1.1
Host: test-service-staging.test.com
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="input"; filename="/C:/Users/DR-11/Downloads/response_1592912235925.xml"
Content-Type: text/xml

(data)
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="format_source"

abc
----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="format_target"

xyz
----WebKitFormBoundary7MA4YWxkTrZu0gW

Curl:

curl --location --request POST 'http://test-service-staging.test.com/convert' \
--form 'input=@/C:/Users/DR-11/Downloads/response_1592912235925.xml' \
--form 'format_source=abc' \
--form 'format_target=xyz'

Instead of file path, need to pass the bytes in the API.

Upvotes: 1

Views: 8286

Answers (1)

traveler3468
traveler3468

Reputation: 1656

Ok, Here is an example of your postman request using HttpClient.
It was hard to test this without a live url, however this should hopefully help you.

Not sure if you are wanting a string or byte array for the return type, I have chosen a string however if you do want a byte array, something like this should do the trick

static async System.Threading.Tasks.Task<byte[]> SendDataAsync()
return await httpResponseMessage.Content.ReadAsByteArrayAsync();

    static async System.Threading.Tasks.Task Main(string[] args)
    {
        // Is This Returning A String Or Bytes
        string responseAsString = await SendDataAsync();
        Console.ReadKey();
    }

    static async System.Threading.Tasks.Task<string> SendDataAsync()
    {
        using (HttpClient httpClient = new HttpClient())
        using (MultipartFormDataContent formDataContent = new MultipartFormDataContent())
        {
            // Create Form Values
            KeyValuePair<string, string>[] keyValuePairs = new[]
            {
                new KeyValuePair<string, string>("format_source", "abc"),
                new KeyValuePair<string, string>("format_target", "xyz")
            };

            // Loop Each KeyValuePair Item And Add It To The MultipartFormDataContent.
            foreach (var keyValuePair in keyValuePairs)
            {
                formDataContent.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
            }

            // Get The ByteArrayContent,Reading Bytes From The Give File Path.
            // Adding It To The MultipartFormDataContent Once File Is Read.
            string filePath = @"C:\Users\andrew.eberle\Desktop\data.xml";
            ByteArrayContent fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(filePath));

            // Add Content Type For MediaTypeHeaderValue.
            fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            // Add The File Under ''input'
            formDataContent.Add(fileContent, "input", System.IO.Path.GetFileName(filePath));

            // Post Request And Wait For The Response.
            HttpResponseMessage httpResponseMessage = await httpClient.PostAsync("http://test-service-staging.test.com/convert", formDataContent);

            // Check If Successful Or Not.
            if (httpResponseMessage.IsSuccessStatusCode)
            {
                // Return Byte Array To The Caller.
                return await httpResponseMessage.Content.ReadAsStringAsync();
            }
            else
            {
                // Throw Some Sort of Exception?
                return default;
            }
        }
    }

Upvotes: 1

Related Questions