c sharp http请求方法的实现
时间: 2024-05-15 21:16:42 浏览: 94
C# HTTP请求示例(采用原始函数实现,运行稳定)
以下是C#中实现HTTP请求的方法:
1. 使用WebRequest和WebResponse类:
```
string url = "http://example.com/api";
WebRequest request = WebRequest.Create(url);
request.Method = "GET";
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
```
2. 使用HttpClient类:
```
string url = "http://example.com/api";
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(url);
string result = await response.Content.ReadAsStringAsync();
```
3. 使用HttpWebRequest类:
```
string url = "http://example.com/api";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
```
以上是三种常用的HTTP请求的实现方法,具体实现方法根据需要选择。
阅读全文