5

我有这段代码,我正在尝试将其转换为 RestSharp。为了清楚起见,我删除了 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();
}

我尝试了以下顺序:

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 发布请求,发送 POST 请求的正确格式是application/x-form-urlencoded什么?

4

1 回答 1

6

所以事实证明参数都已经在数据字符串中序列化了。而我需要手动将它们添加到 RestSharp 请求中。

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

其中数据是键/值对结构

于 2013-05-01T16:26:33.933 回答