C#中的HttpWebRequest类用法详解
简述
HttpWebRequest类是.NET Framework提供的一个用于发起HTTP请求的类。通过HttpWebRequest可以模拟HTTP客户端与服务器间的通信,发送任何形式的HTTP请求,并获取服务器的返回数据。
常用方法和属性
方法
GetResponse()
发起Http请求并获取响应。
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
GetRequestStream()
获取请求流,用于发送POST请求的数据。
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
string jsonData = "{\"username\":\"admin\",\"password\":\"123456\"}";
using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(jsonData);
}
属性
Timeout
请求超时时间。
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 5000; // 5秒超时
UserAgent
请求的User Agent。
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36";
示例说明
发起GET请求并获取响应数据
string url = "https://jsonplaceholder.typicode.com/posts";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
Console.WriteLine(result);
}
发起GET请求需要拼接在URL上,通过Create()创建HttpWebRequest实例后,使用GetResponse()方法发起请求并获取响应数据。最后使用StreamReader类将响应数据以字符串的方式读取出来。
发起POST请求并获取响应数据
string url = "https://jsonplaceholder.typicode.com/posts";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
string jsonData = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";
using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(jsonData);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
Console.WriteLine(result);
}
发起POST请求需要设置请求方法为POST,设置请求头的ContentType属性为"application/json",并将请求数据以字符串的形式写入请求流中。在获取响应数据时,方法同样是使用GetResponse(),使用StreamReader将响应数据读取出来。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C#中的HttpWebRequest类用法详解 - Python技术站