Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringContent Vs FormUrlEncodedContent

Tags:

c#

http-post

I have a URL I want to post a body with parameters to such in the form of data="blahblahblah". However, my "blahblahblah" in this case is a full fledged XML, I simple it down to something like below:

      <Parent id="1">
         <Child id="1"/>
      </Parent>

I can get this to work fine with HTTPClient FormUrlEncodedContent using the following approach.

        var values = new List<KeyValuePair<string, string>>();
        values.Add(new KeyValuePair<string, string>("data", XMLBody));
        var content = new FormUrlEncodedContent(values);
        HttpResponseMessage sResponse = await sClient.PostAsync(action.URL, content).ConfigureAwait(false);

Now I want to get this to work with StringContent. To basically sending xml as part of a parameter value, and that xml contains the "=" . The code below doesn't work, as in I can post it but the server isn't recognize the xml data. Am I doing something wrong here?

StringContent content = new StringContent(HttpUtility.UrlEncode(action.Body), Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage sResponse = await sClient.PostAsync(action.URL, content ).ConfigureAwait(false);
like image 909
Fylix Avatar asked Dec 17 '14 17:12

Fylix


1 Answers

I found it, I have to manually put in the data= part.

StringContent content = new StringContent("data="+ HttpUtility.UrlEncode(action.Body), Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage sResponse = await sClient.PostAsync(action.URL, content ).ConfigureAwait(false);
like image 57
Fylix Avatar answered Oct 22 '22 12:10

Fylix