在C#中,你可以使用WebRequest
類來發送HTTP請求并獲取響應。以下是一個簡單的示例,展示了如何使用WebRequest
類發起GET和POST請求:
using System;
using System.IO;
using System.Net;
using System.Text;
class Program
{
static void Main()
{
// 發起GET請求
string getResponse = GetRequest("https://api.example.com/data");
Console.WriteLine("GET Response: " + getResponse);
// 發起POST請求
string postData = "key1=value1&key2=value2";
string postResponse = PostRequest("https://api.example.com/data", postData);
Console.WriteLine("POST Response: " + postResponse);
}
static string GetRequest(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/json";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
static string PostRequest(string url, string data)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
byte[] postDataBytes = Encoding.ASCII.GetBytes(data);
request.ContentLength = postDataBytes.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(postDataBytes, 0, postDataBytes.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
}
在這個示例中,我們定義了兩個方法:GetRequest
和PostRequest
。GetRequest
方法用于發起GET請求,而PostRequest
方法用于發起POST請求。這兩個方法都接受一個URL參數,并返回響應的字符串。
在GetRequest
方法中,我們創建了一個HttpWebRequest
對象,并設置了請求方法為"GET"。然后,我們使用GetResponse
方法獲取響應,并使用StreamReader
讀取響應內容。
在PostRequest
方法中,我們首先將POST數據轉換為字節數組,然后設置請求的內容類型為"application/x-www-form-urlencoded"。接下來,我們使用GetRequestStream
方法獲取請求的流,并將POST數據寫入流中。最后,我們使用GetResponse
和StreamReader
讀取響應內容。