在C#中,WebRequest是一个非常有用的类,它提供了一种发送Web请求和接收Web响应的方法。你可以使用WebRequest来与Web服务器及其他云服务进行通信,获取数据和文件等。下面是一个演示如何使用WebRequest发送HTTP请求的示例:
创建WebRequest对象
我们可以使用WebRequest.Create(string url)方法来创建一个WebRequest对象。在这里,url是请求的URL地址。例如:
WebRequest request = WebRequest.Create("http://example.com/");
添加请求头
在需要时,我们可以添加请求头到WebRequest对象中。例如:
request.Headers.Add("Authorization", "Bearer token");
发送请求
我们可以使用WebRequest.GetResponse()方法来发送请求并返回响应。例如:
WebResponse response = request.GetResponse();
处理响应
一旦获得了响应对象,我们可以使用WebResponse.GetResponseStream()方法获取一个流来读取响应内容。我们也可以从响应头中获取响应码(StatusCode)、请求地址(ResponseUri)和其它元数据。例如:
Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); Console.WriteLine(responseFromServer); Console.WriteLine(response.StatusCode); Console.WriteLine(response.ResponseUri);
完整的示例代码如下:
try { // Create a request for the URL. WebRequest request = WebRequest.Create("http://example.com/"); // If required by the server, set the credentials. request.Credentials = CredentialCache.DefaultCredentials; // Set the headers for the request request.Headers.Add("Authorization", "Bearer token"); // Get the response. WebResponse response = request.GetResponse(); // Display the status. Console.WriteLine(((HttpWebResponse)response).StatusDescription); // Get the stream containing content returned by the server. Stream dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream); // Read the content. string responseFromServer = reader.ReadToEnd(); // Display the content. Console.WriteLine(responseFromServer); // Clean up the streams and the response. reader.Close(); dataStream.Close(); response.Close(); } catch (WebException e) { Console.WriteLine("Error: " + e.Message); }
注意,在使用WebRequest时,需要确保你的网络连接是安全的且浪费的数据尽量少。大量发送请求可能会导致你被封禁或其它网络相关问题。