在C#中,您可以使用WebClient
類來發送HTTP請求。以下是一個簡單的示例,展示了如何使用WebClient
發送GET和POST請求:
using System;
using System.Net;
using System.IO;
namespace WebClientExample
{
class Program
{
static void Main(string[] args)
{
// 發送GET請求
string getResponse = SendGetRequest("https://api.example.com/data");
Console.WriteLine("GET Response: " + getResponse);
// 發送POST請求
string postData = "key1=value1&key2=value2";
string postResponse = SendPostRequest("https://api.example.com/data", postData);
Console.WriteLine("POST Response: " + postResponse);
}
static string SendGetRequest(string url)
{
using (WebClient webClient = new WebClient())
{
return webClient.DownloadString(url);
}
}
static string SendPostRequest(string url, string data)
{
using (WebClient webClient = new WebClient())
{
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
return webClient.UploadString(url, dataBytes);
}
}
}
}
在這個示例中,我們定義了兩個方法:SendGetRequest
和SendPostRequest
。SendGetRequest
方法接受一個URL參數,并使用WebClient
的DownloadString
方法發送GET請求。SendPostRequest
方法接受一個URL和一個數據字符串參數,將數據字符串轉換為字節數組,并設置內容類型為application/x-www-form-urlencoded
,然后使用WebClient
的UploadString
方法發送POST請求。