Reputation: 349
I have this code which I am attempting to convert to RestSharp. I have removed the using blocks to condense 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 to the order of:
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 can't seem to POST a request using RestSharp, what's the right format to send a POST request in application/x-form-urlencoded
?
Upvotes: 5
Views: 15421
Reputation: 349
So it turns out the parameters were all already serialized in the data string. Whereas I needed to add them to the RestSharp request manually.
foreach (var pair in data)
{
request.AddParameter(pair.Key, pair.Value);
}
where data is a Key/Value pair struct
Upvotes: 6