Search code examples
c#.netwinformsdotnet-httpclient

HttpClient Post request not sending post parameters in C#


I'm sending a post request in my console application but it seems the it is unable to send the post parameters. Here is my code:

static void HttpTest()
{
    string pass_url = "https://staging.fooddesk.be/api/v1/add_new_partner_pws";
    string postString = "[{\n\"product_name\": \"kip absrert\",\n\"producer_name\": \"Imperial Meat Products\",\n\"producer_art_num\": \"123\",\n\"supplier_name\": \"Vagro\",\n\"supplier_art_num\": \"12345\",\n\"ean_code\": \"5411153011327\",\n\"partner_art_nbr\": \"12345\"\n}]\"";
    var multipartContent = new MultipartFormDataContent();
    multipartContent.Add(new StringContent("pws_data" ) , postString) ;
    Uri requestUri = new Uri(pass_url);
    using (var objClint = new System.Net.Http.HttpClient())
    {
        objClint.DefaultRequestHeaders.Add("X-API-KEY", "ABCD");
        objClint.DefaultRequestHeaders.Add("X-COMP-KEY", "XYZ");
        System.Net.Http.HttpResponseMessage response = objClint.PostAsync(requestUri, multipartContent).Result;
        Console.WriteLine(response);
        if (response.IsSuccessStatusCode)
        {
            string json = response.Content.ReadAsStringAsync().Result;
            Console.WriteLine(json);
        }
    }
}

I'm getting an exception at line number 4. Please let me know how should I send the post data in http client post request.


Solution

  • I believe you are mixing up your arguments in line 4.

    Look at the docs for usage.

    Try

    multipartContent.Add(new StringContent(postString) , "pws_data") ;
    

    Also, the post string has an extra quote at the end after ]. Removing that should help.

    [{ "product_name": "kip absrert", "producer_name": "Imperial Meat Products", "producer_art_num": "123", "supplier_name": "Vagro", "supplier_art_num": "12345", "ean_code": "5411153011327", "partner_art_nbr": "12345" }]"