HTTP POST web isteği nasıl yapılır

Kanonik
Nasıl bir HTTP isteği yapabilir ve POST` **metodunu kullanarak bazı verileri gönderebilirim?

GETisteği yapabiliyorum ama nasılPOST` yapılacağı hakkında bir fikrim yok.

Çözüm

HTTP GET ve POST isteklerini gerçekleştirmenin birkaç yolu vardır:


Yöntem A: HttpClient (Tercih Edilen)

Bu, HttpWebRequest etrafında bir sarmalayıcıdır. WebClient` ile karşılaştırın.

Mevcut: .NET Framework 4.5+, .NET Standard 1.1+, .NET Core 1.0+.

Şu anda tercih edilen yaklaşım. Eşzamansız. Diğer platformlar için taşınabilir sürüm NuGet aracılığıyla kullanılabilir.

using System.Net.Http;

Kurulum

Uygulamanızın ömrü boyunca bir HttpClient örneklemesi yapmanız ve bunu paylaşmanız önerilir.

private static readonly HttpClient client = new HttpClient();

Dependency Injection çözümü için HttpClientFactory bölümüne bakın.


  • POST

      var değerler = new Dictionary
      {
      { "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();
  • GET

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

Yöntem B: 3. Taraf Kütüphaneleri

REST API'leri ile etkileşim için denenmiş ve test edilmiş kütüphane. Taşınabilir. NuGet](https://www.nuget.org/packages/RestSharp) aracılığıyla kullanılabilir.

Akıcı bir API ve test yardımcıları içeren daha yeni bir kütüphane. Kaputun altında HttpClient. Taşınabilir. NuGet](https://www.nuget.org/packages/Flurl.Http) aracılığıyla kullanılabilir.

    using Flurl.Http;

  • POST

      var responseString = await "http://www.example.com/recepticle.aspx"
          .PostUrlEncodedAsync(new { şey1 = "hello", şey2 = "world" })
          .ReceiveString();
  • GET

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

Yöntem C: HttpWebRequest (Yeni çalışmalar için önerilmez)

Mevcut: .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=" + Uri.EscapeDataString("hello");
          postData += "&thing2=" + Uri.EscapeDataString("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();
  • GET

      var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
    
      var response = (HttpWebResponse)request.GetResponse();
    
      var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

Yöntem D: WebClient (Yeni çalışmalar için önerilmez)

Bu, HttpWebRequest etrafında bir sarmalayıcıdır. HttpClient ile karşılaştırın.

Mevcut: .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);
      }
  • GET

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

Basit GET isteği

using System.Net;

...

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

Basit POST isteği

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

MSDN'de bir örnek bulunmaktadır.

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