HttpClient を使用した C# での cURL リクエストの作成
C# での cURL リクエストの作成は、多くのアプリケーションで共通の要件です。単純なタスクのように思えるかもしれませんが、cURL コマンドを HTTP リクエストに変換し、C# コードから送信するのは難しい場合があります。
C# で cURL リクエストを作成するには、HttpWebRequest などのさまざまなメソッドを利用できます。 /HttpWebResponse、WebClient、または HttpClient。ただし、使いやすさと堅牢性が向上しているため、HttpClient が推奨されます。
次の cURL コマンドの例を考えてみましょう。
curl -d "text=This is a block of text" \ http://api.repustate.com/v2/demokey/score.json
このコマンドを C# の HTTP リクエストに変換するには、HttpClient を使用します。次の手順に従ってください:
using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace CurlExample { class Program { async static Task Main(string[] args) { var client = new HttpClient(); client.BaseAddress = new Uri("http://api.repustate.com/v2/"); // Create content for JSON request var content = new StringContent("{\n \"text\": \"This is a block of text\"\n}"); content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send the request var response = await client.PostAsync("demokey/score.json", content); // Get the response content var responseContent = await response.Content.ReadAsStringAsync(); // Output the response content Console.WriteLine(responseContent); } } }
この例では、コンテンツはcontent 変数が PostAsync メソッドに渡されます。 responseContent.ReadAsStringAsync() を呼び出すことで、JSON 応答を文字列として取得して表示します。
以上がHttpClient を使用して C# で cURL リクエストを作成するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。