use of application/x-www-form-urlencoded in POST method, HttpClient

17,042

Assuming your keys don't need encoding (ie. don't include any characters that are special in URIs), where fields in a collection of name-value pairs with the values already converted to strings):

var httpBody = String.Join('&', 
                  fields.Select(nv => 
                     String.Concat(nv.Name,
                                   "=",
                                   WebUtility.UrlEncode(nv.Value))));

and then use the applicable encoding to serialise into the HttpWebRequest body.

Share:
17,042
Admin
Author by

Admin

Updated on June 13, 2022

Comments

  • Admin
    Admin almost 2 years

    What if I have this data to send: Post parameters:

    access_token access_token_Value

    list Array of array(with 4 pairs of arg)

    arg1 arg1_value

    arg2 arg2_value

    arg3 arg3_value

    arg4 arg4_value

    and in specification is this (All possible enumerated values in both POST parameters and returned arrays are specified in this document and separated by vertical bars ||). I have Universal Windows app project. How convert this data to "application/x-www-form-urlencoded" format? To ordinary pairs like key-value i use

        var body = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("arg1", "arg1value"),
            new KeyValuePair<string, string>("arg2", "arg2value"),
            new KeyValuePair<string, string>("arg3", "arg3value"),
            new KeyValuePair<string, string>("arg4", "arg4value")
        };
    
        var content = new FormUrlEncodedContent(body);
        var result = httpClient.PostAsync(uri, content).Result;
    

    and this is ok (transmitted data: arg1=arg1value&arg2=arg2value&....), but what if the data are the same as I wrote at the beginning of this post?