在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 = "https://www.yisu.com/ask/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
读取响应内容。