HttpClientHelper帮助类

using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WCSInterfaceWindowsService
{
    public class HttpClientHelper
    {
        public static readonly HttpClientHelper _instance = new HttpClientHelper();

        public HttpClientHelper() { }

        public static HttpClientHelper GetInstance()
        {
            return _instance;
        }

        /// <summary>
        /// 通过Get请求数据
        /// </summary>
        /// <returns></returns>
        public static async Task<string> HttpGetMathod()
        {
            var httpClient = new HttpClient();
            var url = "http://localhost:9000/index.html";
            var response = await httpClient.GetAsync(url);
            var result = await response.Content.ReadAsStringAsync();
            return result;
        }

        /// <summary>
        /// 通过Get下载文件
        /// </summary>
        /// <param name="filePath"></param>
        public static async void HttpGetByDownLoadFileMathod(string filePath)
        {
            var httpClient = new HttpClient();
            var response = await httpClient.GetAsync("http://localhost:9000/middledata.mp4");//763M
            var fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
            await response.Content.CopyToAsync(fileStream);
            fileStream.Close();
        }

        /// <summary>
        /// 通过Post请求数据: application/x-www-form-urlencoded
        /// </summary>
        /// <returns></returns>
        public static async Task<string> HttpPostMathod()
        {
            var httpClient = new HttpClient();
            var url = "http://192.168.0.9:9000/Demo/PostUrlCode";
            var response = await httpClient.PostAsync(url, new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
             {
                 new KeyValuePair<string, string>("name","小明"),
                 new KeyValuePair<string, string>("age","20")
             }));
            var result = await response.Content.ReadAsStringAsync();
            return result;
        }

        /// <summary>
        /// 使用Post请求数据:application/json
        /// </summary>
        /// <returns></returns>
        public static async Task<string> HttpPostByJsonMathod()
        {
            var httpClient = new HttpClient();
            var url = "http://192.168.0.9:9000/Demo/PostUrlJson";
            var response = await httpClient.PostAsync(
              url,
             new StringContent(
              Newtonsoft.Json.JsonConvert.SerializeObject(new { Name = "小明", Id = 1 }),
              Encoding.UTF8,
             "application/json")
                );
            var result = await response.Content.ReadAsStringAsync();
            return result;
        }

        /// <summary>
        /// 通过Post上传文件:multipart/form-data
        /// </summary>
        public static async void HttpPostByUploadMathod()
        {
            var httpClient = new HttpClient();
            var url = "http://localhost:9000/Demo/PostMulti";
            var content = new MultipartFormDataContent();
            content.Add(new StringContent("小明"), "name");
            content.Add(new StringContent("18"), "age");
            //注意:要指定filename,即:test.txt,否则后台不认为是一个文件,而是普通的参数
            content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes("e:\\test.txt")), "file", "test.txt");
            var response = await httpClient.PostAsync(url, content);
            var str = await response.Content.ReadAsStringAsync();
        }

        /// <summary>
        /// 上传大文件
        /// </summary>
        public static async void HttpPostByUploadBigMathod()
        {
            var httpClient = new HttpClient();
            httpClient.Timeout = Timeout.InfiniteTimeSpan;
            var url = "http://192.168.0.9:9000/Demo/PostMulti2";
            var content = new MultipartFormDataContent();
            content.Add(new StringContent("小明"), "name");
            content.Add(new StringContent("18"), "age");
            var filepath = @"E:\BaiduNetdiskDownload\Docker实战.pdf";//97.6MB
            filepath = @"E:\BaiduNetdiskDownload\dnSpy_v6.14.zip";//151.6MB
            filepath = @"E:\BaiduNetdiskDownload\dotnetfx35.exe";//231MB
            filepath = @"E:\BaiduNetdiskDownload\Photoshop_13_LS3(cs6)安装包.7z";//1.12GB
            filepath = @"E:\BaiduNetdiskDownload\cn_windows_10_business_editions_version_2004_updated_june_2020_x64_dvd_49d8dbba.iso";//4.83GB
             var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read);
             var streamContent = new StreamContent(fileStream, 2048);
            content.Add(streamContent, "file", "bigdata.db");
            var response = await httpClient.PostAsync(url, content);
            var str = await response.Content.ReadAsStringAsync();
        }
    }

}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个C#中使用HttpClient帮助,包含了常用的HTTP请求方法和一些常见的配置选项: ```csharp using System; using System.Net.Http; using System.Threading.Tasks; public static class HttpClientHelper { private static readonly HttpClient _httpClient = new HttpClient(); public static async Task<string> GetAsync(string url) { var response = await _httpClient.GetAsync(url); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } public static async Task<byte[]> GetByteArrayAsync(string url) { var response = await _httpClient.GetAsync(url); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsByteArrayAsync(); } public static async Task<string> PostAsync(string url, HttpContent content) { var response = await _httpClient.PostAsync(url, content); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } public static async Task<byte[]> PostByteArrayAsync(string url, HttpContent content) { var response = await _httpClient.PostAsync(url, content); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsByteArrayAsync(); } public static async Task<string> PutAsync(string url, HttpContent content) { var response = await _httpClient.PutAsync(url, content); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } public static async Task<byte[]> PutByteArrayAsync(string url, HttpContent content) { var response = await _httpClient.PutAsync(url, content); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsByteArrayAsync(); } public static async Task<string> DeleteAsync(string url) { var response = await _httpClient.DeleteAsync(url); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } public static async Task<byte[]> DeleteByteArrayAsync(string url) { var response = await _httpClient.DeleteAsync(url); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsByteArrayAsync(); } public static void SetTimeout(TimeSpan timeout) { _httpClient.Timeout = timeout; } public static void SetBaseAddress(string baseAddress) { _httpClient.BaseAddress = new Uri(baseAddress); } public static void SetDefaultRequestHeaders(Action<HttpRequestHeaders> action) { action(_httpClient.DefaultRequestHeaders); } } ``` 使用示例: ```csharp // 设置基地址 HttpClientHelper.SetBaseAddress("http://localhost:9000/"); // 设置超时时间 HttpClientHelper.SetTimeout(TimeSpan.FromSeconds(10)); // 设置默认请求头 HttpClientHelper.SetDefaultRequestHeaders(headers => { headers.Add("User-Agent", "HttpClientHelper"); }); // 发送GET请求 var response = await HttpClientHelper.GetAsync("index.html"); var content = await response.Content.ReadAsStringAsync(); // 发送POST请求 var content = new StringContent("Hello, world!"); var response = await HttpClientHelper.PostAsync("api/values", content); var result = await response.Content.ReadAsStringAsync(); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

落魄的佩奇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值