C# Request

 

using System;
using System.IO;
using System.Net;

using System.Text;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
        public static void Main ()
        {
            // Create a request for the URL.
            WebRequest request = WebRequest.Create ("http://www.contoso.com/default.html");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
            // Display the status.
            Console.WriteLine (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);
            // Cleanup the streams and the response.
            reader.Close ();
            dataStream.Close ();
            response.Close ();
        }
    }
}

### 如何在C#中发送HTTP请求 为了展示如何在 C# 中发送 HTTP 请求,下面提供了一个具体的例子,该实例说明了怎样构建并发出 POST 请求,并处理来自服务器的响应。 #### 使用 `HttpClient` 发送 POST 请求 现代推荐的方式是利用 .NET 提供的 `HttpClient` 类来执行网络操作。这里有一个简单的例子,它创建了一个客户端对象用于向指定 URL 发起带有表单编码参数的应用程序/x-www-form-urlencoded类型的POST请求: ```csharp using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; public class HttpPostExample { public static async Task PostDataAsync() { using (var client = new HttpClient()) { var requestUri = "http://example.com/api/resource"; // 准备要提交的数据 var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("key1", "value1"), new KeyValuePair<string, string>("key2", "value2") }); try { HttpResponseMessage response = await client.PostAsync(requestUri, content); // 确认状态码表示成功 response.EnsureSuccessStatusCode(); // 获取响应体作为字符串 string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } catch (HttpRequestException e) { Console.Error.WriteLine($"Request error: {e.Message}"); } } } } ``` 此代码片段定义了一个异步方法 `PostDataAsync()` ,其内部使用 `HttpClient` 来发起一个 POST 请求至给定的目标地址,并传递了一些键值对形式的数据。如果请求失败,则捕获异常并将错误消息打印出来;否则读取服务端返回的内容并显示于控制台上[^2]。 #### 处理其他类型的请求 除了上述介绍的 POST 方法之外,还可以通过调整 `HttpClient` 的调用来支持 GET、PUT 和 DELETE 等不同种类的操作。对于每种类型的操作,都有相应的同步/异步版本的方法可以选用,比如 `GetAsync`, `PutAsync`, 或者 `DeleteAsync`. 例如,若需获取资源列表,可采用如下方式构造 GET 请求: ```csharp HttpResponseMessage getResponse = await client.GetAsync("http://example.com/api/resources"); string resourcesList = await getResponse.Content.ReadAsStringAsync(); Console.WriteLine(resourcesList); ``` 同样地,在更新现有记录时可以选择 PUT 方式上传修改后的实体数据; 而当删除某条目时则应选择 DELETE 动作[^1].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值