简体   繁体   English

如何在RestSharp中发送POST请求?

[英]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.

相关问题 如何在发布请求正文 (RestSharp) 中格式化和发布 Json - How do I format and post Json in the post request body (RestSharp) 如何从发布请求中获得响应? 锐化 - How do i get the response from a post request? Restsharp 给定以下方法,我如何使用 RestSharp 将请求发送到 Bitstamp API? - How do I, given the following methods, send the request to the Bitstamp API using RestSharp? 如何使用 RestSharp 发布请求 - How to POST request using RestSharp 通过代理使用 restsharp 发送 post 请求 - Send post request using restsharp thru proxy 如何通过将 HttpClient 请求转换为 RestSharp 请求来上传文档? - How do I upload document by converting HttpClient request to RestSharp request? 如何使用RestSharp将登录名和密码发布到API? - How do I use RestSharp to POST a login and password to an API? 如何在 Restsharp 中清除请求的所有参数? - How do I clear all parameters of a request in Restsharp? 使用RestSharp,如何使用oAuth2 Bearer令牌执行对ASP.NET Web API的POST请求? - Using RestSharp, how do I execute a POST request to my ASP.NET Web API with an oAuth2 Bearer token? 如何修复“请求失败,状态码为 BadRequest”RestSharp - How do i fix a "Request failed with status code BadRequest" RestSharp
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM