Using the / x -www-form-urlencoded application in the POST method, HttpClient

What to do if I have this data to send: Message parameters:

access_token access_token_Value

list Array array (with 4 arg pairs)

arg1 arg1_value

arg2 arg2_value

arg3 arg3_value

arg4 arg4_value

and in the specification it is (all possible listed values ​​both in the POST parameters and in the returned arrays are indicated in this document and are separated by vertical bars ||). I have a Universal Windows application project. How to convert this data to the format "application / x-www-form-urlencoded"? For regular pairs, such as 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 normal (transmitted data: arg1 = arg1value & arg2 = arg2value & ....), but what if the data is the same as I wrote at the beginning of this post?

+5
source share
1 answer

Assuming your keys do not need to be encoded (i.e. do not include characters that are special in the URI), where the fields in the collection are name-value pairs with 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 serialize to the body of the HttpWebRequest .

+3
source

Source: https://habr.com/ru/post/1213681/


All Articles