Home > Blockchain >  How to use a string already urlencoded on PostAsync?
How to use a string already urlencoded on PostAsync?

Time:11-08

I'm getting the body using a proxy on my computer which gets all specific requests I made to a specific host and resend them to the server using PostAsync. The body looks like this:

string request_body = "jazoest=25476&fb_dtsg=NAcPrG47So0hD5mhwwRfxJpl2Ey0_MYGJ56i7hag-P_t9oHc4SRnzmg:27:1666973204&create_test_app=1&parent_app_id=851841869280804&basic_name=asdsa - Test2&__usid=6-Trkzn9iowut6h:Prkzqwf7zns4o:0-Arkzq8is0tywz-RV=6:F=&__user=100047878717&__a=1&__dyn=7xeUmxa3-Q8zo9E4a2i5U4e1Fx-ewSxu68uxa2e1Ezobo9E984e0G8G6Ehw9-15wfO1YCwjE7R2o4U1eE4aUS1vw4iwBgaohzE2DwiUmwnEfo4a5Ey19zUuw9O0RE5a1qxa1XwnE2Lxiaw4qxa7o-3qazo8U3ywbS1bqo2Yw&__csr=&__req=1m&__hs=19303.BP:devsite_pkg.2.0.0.0.0&dpr=1&__ccg=EXCELLENT&__rev=1006332&__s=v4ezlf%3:wrukmu&__hsi=7163345567570&__comet_req=0&lsd=x_LyfPf8wTksRdG&__aaid=96891893825&ajax_password=302o&confirmed=1"

and i'm storing it in a string variable (it's already urlencoded because I got it from a request). The problem is: I want to make a PostAsync with this body like this:

var result = Client.PostAsync(baseAddress, request_body).Result;

but I can't pass it directly because PostAsync needs HttpContent as body. How can I "convert" this to the right format?

CodePudding user response:

Since you want to actually create a FormUrlEncodedContent object, you'll need to parse the existing data. You can use HttpUtility.ParseQueryString (using System.Web;) for this:

private static FormUrlEncodedContent ParseFormDataToContent(string value)
{
    var formValues = new List<KeyValuePair<string, string>>();

    var parsedValues = HttpUtility.ParseQueryString(value);
    foreach (var key in parsedValues.AllKeys)
    {
        // a=1&a=2&b=3 is valid, so we can have multiple values per key
        string[] parsedItemValues = parsedValues.GetValues(key);
        foreach (var val in parsedItemValues)
        {
            // add an entry for each key
            formValues.Add(new KeyValuePair<string, string>(key, val));
        }
    }

    // create a FormUrlEncodedContent from the list
    return new FormUrlEncodedContent(formValues);
}

Usage:

FormUrlEncodedContent content = ParseFormDataToContent(request_body);
var result = await Client.PostAsync(baseAddress, content);

My other suggestion was to just use the value verbatim and create a StringContent object:

StringContent content = new StringContent(request_body, System.Text.Encoding.UTF8, "application/x-www-url-form encoded");
var result = await Client.PostAsync(baseAddress, content);
  • Related