How to send a POST request to RestSharp?

I have this code that I am trying to convert to RestSharp. I removed use blocks to thicken it for clarity.

using System.IO;
using System.Net;
using RestSharp;

string GetResponse(string url,string data)
{
    var request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    var bytes = Encoding.UTF8.GetBytes(data);
    request.ContentLength = bytes.Length;
    request.GetRequestStream().Write(bytes, 0, bytes.Length);
    var response = (HttpWebResponse)request.GetResponse();
    var stream = response.GetResponseStream();
    if (stream == null) return string.Empty;
    var reader = new StreamReader(stream);
    return reader.ReadToEnd();
}

I tried something of the order:

string GetResponse(string url, string data)
{
    var client = new RestClient(url);
    var request = new RestRequest("", RestSharp.Method.POST);
    request.AddParameter("application/x-www-form-urlencoded", data);
    var response = client.Execute(request);
    return response.Content;
}

I cannot send a POST request using RestSharp, what is the correct format to send a POST request to application/x-form-urlencoded?

+5
source share
1 answer

So, it turns out that all the parameters have already been serialized in the data row. While I needed to add them to the RestSharp request manually.

foreach (var pair in data) 
{ 
    request.AddParameter(pair.Key, pair.Value); 
}

where the data is a key / value pair structure

+5
source

All Articles