• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
我只吃饭不洗碗
博客园    首页    新随笔    联系   管理    订阅  订阅
c# Http请求封装工具类
 1   public class HttpHelper
 2   {
 3       /// <summary>
 4       /// Get the content of a file from the specified URL.
 5       /// </summary>
 6       /// <param name="url">The URL to request.</param>
 7       /// <param name="method">The HTTP request method.</param>
 8       /// <param name="postData">The data for POST requests (optional).</param>
 9       /// <returns>The content of the file.</returns>
10       public static async Task<string> GetFileContent(string url, HttpMethod method, string postData = null)
11       {
12           using (HttpClient client = new HttpClient())
13           {
14               HttpRequestMessage request = new HttpRequestMessage(method, url);
15               if (method == HttpMethod.Post && !string.IsNullOrEmpty(postData))
16               {
17                   request.Content = new StringContent(postData);
18               }
19 
20               HttpResponseMessage response = await client.SendAsync(request);
21               if (response.IsSuccessStatusCode)
22               {
23                   return await response.Content.ReadAsStringAsync();
24               }
25               else
26               {
27                   Console.WriteLine($"Request failed: {response.StatusCode}");
28                   return null;
29               }
30           }
31       }
32 
33       /// <summary>
34       /// Make an HTTP request.
35       /// </summary>
36       /// <param name="baseUrl">The target URL.</param>
37       /// <param name="method">The request method.</param>
38       /// <param name="requestBody">The request body parameters.</param>
39       /// <returns></returns>
40       public static string HttpRequest(string baseUrl, Method method, RestRequest requestBody)
41       {
42           try
43           {
44               var client = new RestClient(baseUrl);
45 
46               requestBody.Method = method;
47               var response = client.Execute(requestBody);
48               if (response.StatusCode == HttpStatusCode.OK)
49               {
50                   return response.Content;
51               }
52 
53               throw new Exception("HTTP request result error: " + response.ErrorMessage);
54           }
55           catch (Exception ex)
56           {
57               throw new Exception("HTTP request failed: " + ex.Message);
58           }
59       }
60   }

请注意,当 response.StatusCode 状态不是ok时,我会抛出异常。如果不符合业务,请自行修改。

源码地址:https://github.com/yycb1994/DotNet.Working.Notes/tree/main/Working.Notes/Working.Tools

posted on 2024-02-22 11:13  我只吃饭不洗碗  阅读(458)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3