首页 文章

如何进行HTTP POST Web请求

提问于
浏览
835

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

10 回答

  • 1667

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

    如果你喜欢流畅的API,你可以使用Tiny.RestClient它可以在Nuget获得

    var client = new TinyRestClient(new HttpClient(), "http://MyAPI.com/api");
    // POST
     var city = new City() { Name = "Paris" , Country = "France"};
    // With content
    var response = await client.PostRequest("City", city).
                    ExecuteAsync<bool>();
    

    希望有所帮助!

  • 13

    这是以JSON格式发送/接收数据的完整工作示例,我使用的是VS2013 Express Edition

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.OleDb;
    using System.IO;
    using System.Linq;
    using System.Net.Http;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Script.Serialization;
    
    namespace ConsoleApplication1
    {
        class Customer
        {
            public string Name { get; set; }
            public string Address { get; set; }
            public string Phone { get; set; }
        }
    
        public class Program
        {
            private static readonly HttpClient _Client = new HttpClient();
            private static JavaScriptSerializer _Serializer = new JavaScriptSerializer();
    
            static void Main(string[] args)
            {
                Run().Wait();
            }
    
            static async Task Run()
            {
                string url = "http://www.example.com/api/Customer";
                Customer cust = new Customer() { Name = "Example Customer", Address = "Some example address", Phone = "Some phone number" };
                var json = _Serializer.Serialize(cust);
                var response = await Request(HttpMethod.Post, url, json, new Dictionary<string, string>());
                string responseText = await response.Content.ReadAsStringAsync();
    
                List<YourCustomClassModel> serializedResult = _Serializer.Deserialize<List<YourCustomClassModel>>(responseText);
    
                Console.WriteLine(responseText);
                Console.ReadLine();
            }
    
            /// <summary>
            /// Makes an async HTTP Request
            /// </summary>
            /// <param name="pMethod">Those methods you know: GET, POST, HEAD, etc...</param>
            /// <param name="pUrl">Very predictable...</param>
            /// <param name="pJsonContent">String data to POST on the server</param>
            /// <param name="pHeaders">If you use some kind of Authorization you should use this</param>
            /// <returns></returns>
            static async Task<HttpResponseMessage> Request(HttpMethod pMethod, string pUrl, string pJsonContent, Dictionary<string, string> pHeaders)
            {
                var httpRequestMessage = new HttpRequestMessage();
                httpRequestMessage.Method = pMethod;
                httpRequestMessage.RequestUri = new Uri(pUrl);
                foreach (var head in pHeaders)
                {
                    httpRequestMessage.Headers.Add(head.Key, head.Value);
                }
                switch (pMethod.Method)
                {
                    case "POST":
                        HttpContent httpContent = new StringContent(pJsonContent, Encoding.UTF8, "application/json");
                        httpRequestMessage.Content = httpContent;
                        break;
    
                }
    
                return await _Client.SendAsync(httpRequestMessage);
            }
        }
    }
    
  • 2

    您可以使用IEnterprise.Easy-HTTP,因为它内置了类解析和查询构建:

    await new RequestBuilder<ExampleObject>()
    .SetHost("https://httpbin.org")
    .SetContentType(ContentType.Application_Json)
    .SetType(RequestType.Post)
    .SetModelToSerialize(dto)
    .Build()
    .Execute();
    

    我是图书馆的作者,所以请随时提问或查看github中的代码

  • 7

    当使用 Windows.Web.Http 名称空间时,对于POST而不是FormUrlEncodedContent,我们编写HttpFormUrlEncodedContent . 响应也是HttpResponseMessage的类型 . 其余的是Evan Mulawski写下来的 .

  • 2

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


    Method A: HttpClient

    适用于:.NET Framework 4.5,.NET Standard 1.1,.NET Core 1.0

    目前首选的方法 . 异步 . 通过NuGet提供的其他平台的便携版本 .

    using System.Net.Http;
    

    Build

    recommended为您的应用程序的生命周期实例化一个 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");
    

    Method B: 3rd-Party Libraries

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

    Method C: Legacy

    适用于:.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();
    

    Method D: WebClient (Also now legacy)

    适用于:.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");
    }
    
  • 53

    您需要使用 WebRequest 类和 GetRequestStream 方法 .

    Here就是一个例子 .

  • 0

    到目前为止我发现的简单(单行,无错误检查,无需等待响应)解决方案

    (new WebClient()).UploadStringAsync(new Uri(Address), dataString);‏
    

    谨慎使用!

  • 325

    这里有一些非常好的答案 . 让我以不同的方式发布使用WebClient()设置 Headers . 我还将向您展示如何设置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);
    
  • 2

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

相关问题