规范如何发出HTTP请求并使用]发送一些数据>
POST
方法?我可以提出
GET
请求,但是我不知道如何提出GET
请求。
规范如何使用POST方法发出HTTP请求并发送一些数据?我可以执行GET请求,但不知道如何发出POST请求。
有几种执行HTTP POST
和POST
请求的方法:
为什么这不完全是琐碎的?进行请求不是,尤其是不处理结果,似乎还涉及到一些.NET错误-参见(new WebClient()).UploadStringAsync(new Uri(Address), dataString);
我最终得到了这段代码:
Tiny.RestClient
简单的GET请求
POST
简单的POST请求
[GET
有一个样本。
using (var client = new WebClient())
{
var responseString = client.DownloadString("http://www.example.com/recepticle.aspx");
}
这是以JSON格式发送/接收数据的完整工作示例,我使用了using System.Net;
...
using (var wb = new WebClient())
{
var response = wb.DownloadString(url);
}
版:
using System.Net;
using System.Collections.Specialized;
...
using (var wb = new WebClient())
{
var data = new NameValueCollection();
data["username"] = "myUser";
data["password"] = "myPassword";
var response = wb.UploadValues(url, "POST", data);
string responseInString = Encoding.UTF8.GetString(response);
}
这里有一些非常好的答案。让我发布一种不同的方法来使用WebClient()设置标题。我还将向您展示如何设置API密钥。
MSDN
此解决方案仅使用标准.NET调用。
已测试:
到目前为止,我已经找到了一种简单的方法(单线,没有错误检查,没有等待响应:
// Add a Reference to the assembly System.Web
请谨慎使用!
使用Windows.Web.Http名称空间时,对于POST而不是FormUrlEncodedContent,我们编写HttpFormUrlEncodedContent。响应也是HttpResponseMessage的类型。其余的就是Evan Mulawski写下的内容。
如果您喜欢流畅的API,则可以使用using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
private async Task<WebResponse> CallUri(string url, TimeSpan timeout)
{
var uri = new Uri(url);
NameValueCollection rawParameters = HttpUtility.ParseQueryString(uri.Query);
var parameters = new Dictionary<string, string>();
foreach (string p in rawParameters.Keys)
{
parameters[p] = rawParameters[p];
}
var client = new HttpClient { Timeout = timeout };
HttpResponseMessage response;
if (parameters.Count == 0)
{
response = await client.GetAsync(url);
}
else
{
var content = new FormUrlEncodedContent(parameters);
string urlMinusParameters = uri.OriginalString.Split('?')[0]; // Parameters always follow the '?' symbol.
response = await client.PostAsync(urlMinusParameters, content);
}
var responseString = await response.Content.ReadAsStringAsync();
return new WebResponse(response.StatusCode, responseString);
}
private class WebResponse
{
public WebResponse(HttpStatusCode httpStatusCode, string response)
{
this.HttpStatusCode = httpStatusCode;
this.Response = response;
}
public HttpStatusCode HttpStatusCode { get; }
public string Response { get; }
}
。在 var timeout = TimeSpan.FromSeconds(300);
WebResponse response = await this.CallUri("http://www.google.com/", timeout);
if (response.HttpStatusCode == HttpStatusCode.OK)
{
Console.Write(response.Response); // Print HTML.
}
var timeout = TimeSpan.FromSeconds(300); WebResponse response = await this.CallUri("http://example.com/path/to/page?name=ferret&color=purple", timeout); if (response.HttpStatusCode == HttpStatusCode.OK) { Console.Write(response.Response); // Print HTML. }
希望有帮助!