wpfpost实例源代码

4. 实例源代码
// 示例代码请根据实际情况修改URL和文件路径
// 发送GET请求
using (HttpClient client = new HttpClient())
{
    HttpResponseMessage response = await client.GetAsync("https://example.com/api/resource");    // 处理响应
}
// 发送POST请求
using (HttpClient client = new HttpClient())
{
    var content = new StringContent("data to send", Encoding.UTF8, "application/json");
    HttpResponseMessage response = await client.PostAsync("https://example.com/api/resource", content);    // 处理响应
}
// 上传文件
using (HttpClient client = new HttpClient())
{
    var content = new MultipartFormDataContent();
    content.Add(new ByteArrayContent(File.ReadAllBytes("file.txt")), "file", "file.txt");
    HttpResponseMessage response = await client.PostAsync("https://example.com/api/upload", content);    // 处理响应
}
// 下载文件
using (HttpClient client = new HttpClient())
{
    byte[] fileData = await client.GetByteArrayAsync(" 
    File.WriteAllBytes("downloaded_file.txt", fileData);
}
// 设置
Authorizationusing (HttpClient client = new HttpClient())
{
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "your_access_token");
    HttpResponseMessage response = await client.GetAsync("https://example.com/api/resource");    // 处理响应
}
// 设置
Cookieusing (HttpClient client = new HttpClient())
{
    var cookieContainer = new CookieContainer();
    var handler = new HttpClientHandler { CookieContainer = cookieContainer };
    using (var httpClient = new HttpClient(handler))
    {
        HttpResponseMessage response = await client.GetAsync("https://example.com/api/resource");        // 处理响应
    }
}
5. 注意事项及建议
使用using语句确保及时释放HttpClient资源。

异步方法应避免在同步上下文中使用,以提高性能。

注意处理HTTP响应状态码和异常,确保请求的正确执行。

文件上传和下载时,考虑使用流式传输以节省内存。

通过HttpClient,我们能够在C#中方便地进行HTTP请求操作,包括GET、POST请求、文件上传和下载,以及设置Authorization、cookie等。确保使用异步操作和适当的异常处理,能够保证请求的稳定性和性能。