[英]How do I send a POST request in RestSharp?
I have this code which I am attempting to convert to RestSharp. 我有尝试将其转换为RestSharp的代码。 I have removed the using blocks to condense it for clarity. 为了清楚起见,我删除了using块来压缩它。
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
? 我似乎无法使用RestSharp发布请求,以application/x-form-urlencoded
发送POST请求的正确格式是什么?
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. 而我需要将它们手动添加到RestSharp请求中。
foreach (var pair in data)
{
request.AddParameter(pair.Key, pair.Value);
}
where data is a Key/Value pair struct 其中数据是键/值对结构
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.