如何制作HTTP POST Web请求

如何使用POST方法发出HTTP请求并发送一些数据? 我可以做GET请求,但不知道如何进行POST


有几种方法可以执行HTTP GETPOST请求:


方法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();

POST

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 = await response.Content.ReadAsStringAsync();

得到

var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");

方法B:第三方库

RestSharp

尝试并测试了与REST API交互的库。 便携。 通过NuGet提供。

Flurl.Http

较新的图书馆运动流畅的API和测试助手。 引擎盖下的HttpClient。 便携。 通过NuGet提供。

using Flurl.Http;

POST

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:遗留

可用于:.NET Framework 1.1+,.NET Standard 2.0+,.NET Core 1.0+

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

POST

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");

var postData = "thing1=hello";
    postData += "&thing2=world";
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

var response = (HttpWebResponse)request.GetResponse();

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

得到

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");

var response = (HttpWebResponse)request.GetResponse();

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

方法D:WebClient(现在也是传统)

可用于:.NET Framework 1.1+,.NET Standard 2.0+,.NET Core 2.0+

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

POST

using (var client = new WebClient())
{
    var values = new NameValueCollection();
    values["thing1"] = "hello";
    values["thing2"] = "world";

    var response = client.UploadValues("http://www.example.com/recepticle.aspx", values);

    var responseString = Encoding.Default.GetString(response);
}

得到

using (var client = new WebClient())
{
    var responseString = client.DownloadString("http://www.example.com/recepticle.aspx");
}

简单的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);
}

MSDN有一个示例。

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestPostExample
    {
        public static void Main()
        {
            // Create a request using a URL that can receive a post. 
            WebRequest request = WebRequest.Create("http://www.contoso.com/PostAccepter.aspx");
            // Set the Method property of the request to POST.
            request.Method = "POST";
            // Create POST data and convert it to a byte array.
            string postData = "This is a test that posts this string to a Web server.";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;
            // Get the request stream.
            Stream dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close();
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();
        }
    }
}
链接地址: http://www.djcxy.com/p/7031.html

上一篇: How to make HTTP POST web request

下一篇: Custom HTTP headers : naming conventions