HTTP POSTのWebリクエストの作り方

Canonical
POSTメソッドを使用して、HTTPリクエストを行い、データを送信するにはどうすればよいですか**?

GETのリクエストはできますが、POST`の作り方がわかりません。

ソリューション

HTTPの GET および POST リクエストを実行する方法はいくつかあります。


方法 A:HttpClient (推奨)

これは HttpWebRequest のラッパーです。WebClient`との比較です。

次のバージョンで利用できます。.NET Framework 4.5+,.NET Standard 1.1+,.NET Core 1.0+` .

現在推奨されている方法です。非同期式です。他のプラットフォーム用のポータブル版はNuGetから入手可能です。

using System.Net.Http;

セットアップ

アプリケーションの存続期間中、1つのHttpClientをインスタンス化して共有することが推奨されています。

private static readonly HttpClient client = new HttpClient();

依存性注入のソリューションについては、HttpClientFactoryを参照してください。


  • POST

      var values = 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");

方法 B: サードパーティのライブラリ

REST APIを操作するための試行錯誤されたライブラリです。ポータブルです。NuGet](https://www.nuget.org/packages/RestSharp)から入手可能です

流れるような API とテスト用のヘルパーを備えた新しいライブラリです。フードの下には HttpClient が入っています。ポータブルです。NuGet](https://www.nuget.org/packages/Flurl.Http)で入手可能です

    Flurl.Http.Client を使用しています。

  • POST

      var responseString = await "http://www.example.com/recepticle.aspx"
          .PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
          .ReceiveString();
  • GET です。

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

方法C: HttpWebRequest (新しい作品にはお勧めしません)

以下のバージョンで利用可能です。.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();

方法D:WebClient (新規案件には推奨しません)

これは HttpWebRequest のラッパーです。HttpClient`との比較です。

利用できる環境.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");
      }
解説 (35)

シンプルな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);
}
解説 (12)

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