我如何能使一个HTTP POST请求和发送数据的主体?


当前回答

这里有一些非常好的答案。让我发布一种不同的方法来设置你的头部与WebClient()。我还将向您展示如何设置API键。

        var client = new WebClient();
        string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord));
        client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";
        //If you have your data stored in an object serialize it into json to pass to the webclient with Newtonsoft's JsonConvert
        var encodedJson = JsonConvert.SerializeObject(newAccount);

        client.Headers.Add($"x-api-key:{ApiKey}");
        client.Headers.Add("Content-Type:application/json");
        try
        {
            var response = client.UploadString($"{apiurl}", encodedJson);
            //if you have a model to deserialize the json into Newtonsoft will help bind the data to the model, this is an extremely useful trick for GET calls when you have a lot of data, you can strongly type a model and dump it into an instance of that class.
            Response response1 = JsonConvert.DeserializeObject<Response>(response);

其他回答

在. net Core中,你可以用下面的代码进行POST调用。在这里,我为这段代码添加了一些额外的特性,这样您就可以让您的代码在代理后工作,如果有网络凭据的话。

在这里我还提到,您可以更改消息的编码。

HttpClient client = GetHttpClient(_config);

if (headers != null)
{
    foreach (var header in headers)
    {
        client.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
    }
}

client.BaseAddress = new Uri(baseAddress);

Encoding encoding = Encoding.UTF8;

var result = await client.PostAsync(url, new StringContent(body, encoding, "application/json")).ConfigureAwait(false);
if (result.IsSuccessStatusCode)
{
    return new RequestResponse { severity = "Success", httpResponse = result.Content.ReadAsStringAsync().Result, StatusCode = result.StatusCode };
}
else
{
    return new RequestResponse { severity = "failure", httpResponse = result.Content.ReadAsStringAsync().Result, StatusCode = result.StatusCode };
}


public HttpClient GetHttpClient(IConfiguration _config)
{
    bool ProxyEnable = Convert.ToBoolean(_config["GlobalSettings:ProxyEnable"]);

    HttpClient client = null;
    if (!ProxyEnable)
    {
        client = new HttpClient();
    }
    else
    {
        string ProxyURL = _config["GlobalSettings:ProxyURL"];
        string ProxyUserName = _config["GlobalSettings:ProxyUserName"];
        string ProxyPassword = _config["GlobalSettings:ProxyPassword"];
        string[] ExceptionURL = _config["GlobalSettings:ExceptionURL"].Split(';');
        bool BypassProxyOnLocal = Convert.ToBoolean(_config["GlobalSettings:BypassProxyOnLocal"]);
        bool UseDefaultCredentials = Convert.ToBoolean(_config["GlobalSettings:UseDefaultCredentials"]);

        WebProxy proxy = new WebProxy
        {
            Address = new Uri(ProxyURL),
            BypassProxyOnLocal = BypassProxyOnLocal,
            UseDefaultCredentials = UseDefaultCredentials,
            BypassList = ExceptionURL,
            Credentials = new NetworkCredential(ProxyUserName, ProxyPassword)
        };

        HttpClientHandler handler = new HttpClientHandler { Proxy = proxy };
        client = new HttpClient(handler, true);
    }
    return client;
}

简单的GET请求

using System.Net;

...

using (var wb = new WebClient())
{
    var response = wb.DownloadString(url);
}

简单的POST请求

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);
}

执行HTTP GET和POST请求有几种方法:


方法A: HttpClient(首选)

支持。net Framework 4.5+, . net Standard 1.1+, . net Core 1.0+。

它是目前首选的方法,并且是异步的和高性能的。在大多数情况下使用内置版本,但对于非常老的平台,有一个NuGet包。

using System.Net.Http;

设置

建议为应用程序的生命周期实例化一个HttpClient并共享它,除非您有特定的理由不这样做。

private static readonly HttpClient client = new HttpClient();

请参阅HttpClientFactory以获得依赖注入解决方案。


帖子 var values = new Dictionary<string, string> { {"thing1", "hello"}, {"thing2", "world"} }; var content = new FormUrlEncodedContent(values); var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content); var responseString =等待response.Content.ReadAsStringAsync(); 得到 var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");


方法B:第三方库

休息夏普

帖子 var client = new RestClient("http://example.com"); / /客户端。Authenticator =新的HttpBasicAuthenticator(用户名,密码); var request = new RestRequest("resource/{id}"); 请求。AddParameter(“thing1”、“你好”); 请求。AddParameter(“事件”、“世界”); 请求。AddHeader(“标题”、“价值”); 请求。AddFile(“文件”,路径); var response = client.Post(请求); var content = response.Content;//原始内容为字符串 var response2 = client.Post<Person>(request); var name = response2.Data.Name;

Flurl。Http

它是一个更新的库,拥有一个流畅的API,测试助手,在底层使用HttpClient,并且是可移植的。它可以通过NuGet获得。

    using Flurl.Http;

帖子 var responseString = await“http://www.example.com/recepticle.aspx” .PostUrlEncodedAsync(new {thing1 = "hello", thing2 = "world"}) .ReceiveString (); 得到 var responseString = await“http://www.example.com/recepticle.aspx” .GetStringAsync ();


方法C: HttpWebRequest(不推荐用于新工作)

支持。net Framework 1.1+, . net Standard 2.0+, . net Core 1.0+。在。net Core中,它主要是为了兼容性——它包装了HttpClient,性能较差,并且不会获得新的特性。

using System.Net;
using System.Text;  // For class Encoding
using System.IO;    // For StreamReader

发布 var request = (HttpWebRequest)WebRequest.Create(“http://www.example.com/recepticle.aspx”); var postData = “thing1=” + Uri.EscapeDataString(“hello”); postData += “&thing2=” + Uri.EscapeDataString(“world”); var data = Encoding.ASCII.GetBytes(postData); 请求。方法 =“开机自检”; 请求。ContentType = “application/x-www-form-urlencoded”; 请求。内容长度 = 数据。长度; 使用 (var 流 = 请求。GetRequestStream()) { 流。写入(数据, 0, 数据.长度); } var response = (HttpWebResponse)request.获取响应(); var responseString = new StreamReader(response.GetResponseStream())。ReadToEnd(); 获取 var request = (HttpWebRequest)WebRequest.Create(“http://www.example.com/recepticle.aspx”); var response = (HttpWebResponse)request.获取响应(); var responseString = new StreamReader(response.GetResponseStream())。ReadToEnd();


方法D: WebClient(不推荐新作品)

这是一个HttpWebRequest的包装器。与HttpClient比较。

支持。NET Framework 1.1+, NET Standard 2.0+和。NET Core 2.0+。

在某些情况下…NET Framework 4.5-4.8),如果你需要同步地做一个HTTP请求,WebClient仍然可以使用。

using System.Net;
using System.Collections.Specialized;

帖子 使用(var client = new WebClient()) { var values = new NameValueCollection(); 值["thing1"] = "hello"; Values ["thing2"] = "world"; var response = client.UploadValues("http://www.example.com/recepticle.aspx", values); var responseString = Encoding.Default.GetString(response); } 得到 使用(var client = new WebClient()) { var responseString = client.DownloadString("http://www.example.com/recepticle.aspx"); }

如果需要POST JSON消息体,可以使用以下方法。假设您有一个名为m的类实例。

string jsonMessage = JsonConvert.SerializeObject(m);

// Make POST call
using (HttpClient client = new HttpClient())
{
    HttpRequestMessage requestMessage = new
    HttpRequestMessage(HttpMethod.Post, "<url here>");
    requestMessage.Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json");
    HttpResponseMessage response = client.SendAsync(requestMessage).Result;
    if (response.StatusCode == System.Net.HttpStatusCode.OK)
    {
        // Do something here
    }
}

当使用Windows.Web.Http命名空间时,对于POST而不是FormUrlEncodedContent,我们编写HttpFormUrlEncodedContent。同样,响应类型为HttpResponseMessage。其余的就像Evan Mulawski写的那样。