Http post request with Content-Type: application/x-www-form-urlencoded

5.6k Views Asked by At

How to sent POST request with content-type = application/x-www-form-urlencoded. Given an access code, I am trying to get the AccessToken using POST request where I have all the information set in POST URL so i don't know what to pass as Http content in the postAysnc method.

According to another post For application/x-www-form-urlencoded, the body of the HTTP message sent to the server is essentially one giant query string -- name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be:

MyVariableOne=ValueOne&MyVariableTwo=ValueTwo.

So I have similar case where my POST url has all the information as querystring, in that case I don't know what to pass as HttpContent in the postAysnc method since its a mandatory parameter

HttpClient client = new HttpClient(); StringContent queryString = new StringContent(data); HttpResponseMessage response = await client.PostAsync(new Uri(url), queryString );

1

There are 1 best solutions below

0
Mark Sowul On

Two options:

  1. Continue to use StringContent, but set the content type: new StringContent(data, Encoding.UTF8, "application/x-www-form-urlencoded")
  2. Instead of using StringContent, use FormUrlEncodedContent; note that this takes in a sequence of KeyValuePair<string, string> describing the values (so for example create a dictionary containing { {"MyVariableOne", "ValueOne"}, {"MyVariableTwo", "ValueTwo"} }