Posting Name Value Pairs with HttpClient

Kmcnet 706 Reputation points

Hello everyone and thanks for the help in advance. I am writing an application that needs to POST Name-Value pairs along with some header details to an external api. Here is my code to this point:

            HttpClient client = new HttpClient();  
            NameValueCollection nameValueCollection = new NameValueCollection();  
            nameValueCollection.Add("media_url", "");  
            nameValueCollection.Add("connection_id", "12345678");  
            nameValueCollection.Add("to", "+19999999999");  
            nameValueCollection.Add("from", "+19999999999");  
            var webRequest = new HttpRequestMessage(HttpMethod.Post, "")  
                Content = new StringContent(nameValueCollection.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded")  
            webRequest.Headers.Add("Authorization", "Bearer KEY12345");  
            var response = client.Send(webRequest);  
            var reader = new StreamReader(response.Content.ReadAsStream());  
            var responseBody = reader.ReadToEnd();  

I am receiving an error message stating the api requires a parameter connection_id. Looks like I'm not transmitting data, but not sure why. Any help would be appreciated.

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,603 questions
{count} votes

Accepted answer
  1. Viorel 114.4K Reputation points

    Try something like this:

    string d = string.Join( "&",  
            .SelectMany( k => nameValueCollection.GetValues( k ).Select( v => $"{Uri.EscapeDataString( k )}={Uri.EscapeDataString( v )}" ) ) );  
    Content = new StringContent(d, Encoding.UTF8, "application/x-www-form-urlencoded");  

    If it works, maybe there are more elegant solutions.

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful