简体   繁体   中英

How to convert application/x-www-form-urlencoded to JSON?

I made http post request with content type application/x-www-form-urlencoded UTF-8 using Httpclient.PostRequest . I need to convert application/x-www-form-urlencoded request result to json string. How can I application/x-www-form-urlencoded to json in C#?

I did next post request.

HttpResponseMessage response;
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://sv.ki.court.gov.ua/new.php"))
{
   request.Headers.TryAddWithoutValidation("Connection", "keep-alive");
   request.Headers.TryAddWithoutValidation("Accept", "application/json, text/javascript, */*; q=0.01");
   request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate, br");
   request.Headers.TryAddWithoutValidation("Accept-Language", "en-US,en;q=0.9");
   request.Headers.TryAddWithoutValidation("Referer", "https://sv.ki.court.gov.ua/sud2608/gromadyanam/csz");
   request.Headers.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36");
   request.Headers.TryAddWithoutValidation("Origin", "https://sv.ki.court.gov.ua");
   request.Headers.TryAddWithoutValidation("X-Requested-With", "XMLHttpRequest");
   request.Headers.TryAddWithoutValidation("Cookie", "_ga=GA1.3.1754947237.1562858299; PHPSESSID=1nosm5dhdljsv8tpsu97bl8dn5; cookiesession1=257F9822DPOYFGLLUDVTJCMDYYR98AB6; _gid=GA1.3.1599643655.1563891940; _gat=1");

   request.Content = new StringContent("q_court_id=2608", Encoding.UTF8, "application/x-www-form-urlencoded");

   response = await _client.SendAsync(request);
}

Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var json = await response.Content.ReadAsStringAsync();

As StringContent type I used application/x-www-form-urlencoded . application/json doesn't work. Post request return result string " \<.... ". I need to convert response result application/x-www-form-urlencoded to application/json

This should give you some idea. In the example below inside PostAsync you pass in a new instance of StringContent where you set the type of content ie in this case Json .

public static async Task MainAsync()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost:1234");
        var content = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("", "Joe Bloggs")
        });
        var result = await client.PostAsync("/api/Customer/exists", new StringContent(content.ToString(), Encoding.UTF8, "application/json"));
        string resultContent = await result.Content.ReadAsStringAsync();
        Console.WriteLine(resultContent);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM