我有这个代码,我试图转换为RestSharp。为了清楚起见,我删除了使用块来压缩它。
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();
}
我按照以下顺序尝试了一些事情:
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;
}
我似乎无法使用RestSharp发送请求,在application/x-form-urlencoded
中发送POST请求的正确格式是什么?
答案 0 :(得分:5)
事实证明,参数都已在数据字符串中序列化。而我需要手动将它们添加到RestSharp请求中。
foreach (var pair in data)
{
request.AddParameter(pair.Key, pair.Value);
}
其中data是键/值对结构