基于HttpClient封装的请求类

using ICSharpCode.SharpZipLib.GZip;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

/// <summary>
/// 基于HttpClient封装的请求类
/// </summary>
public class HttpRequest
{
    /// <summary>
    /// 使用post方法异步请求
    /// </summary>
    /// <param name="url">目标链接</param>
    /// <param name="json">发送的参数字符串,只能用json</param>
    /// <returns>返回的字符串</returns>
    public static async Task<string> PostAsyncJson(string url, string json)
    {
        HttpClient client = new HttpClient();
        HttpContent content = new StringContent(json);
        content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
        HttpResponseMessage response = await client.PostAsync(url, content);
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();
        return responseBody;
    }

    /// <summary>
    /// 使用post方法异步请求
    /// </summary>
    /// <param name="url">目标链接</param>
    /// <param name="data">发送的参数字符串</param>
    /// <returns>返回的字符串</returns>
    public static async Task<string> PostAsync(string url, string data, Dictionary<string, string> header = null, bool Gzip = false)
    {
        HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false });
        HttpContent content = new StringContent(data);
        if (header != null)
        {
            client.DefaultRequestHeaders.Clear();
            foreach (var item in header)
            {
                client.DefaultRequestHeaders.Add(item.Key, item.Value);
            }
        }
        HttpResponseMessage response = await client.PostAsync(url, content);
        response.EnsureSuccessStatusCode();
        string responseBody = "";
        if (Gzip)
        {
            GZipInputStream inputStream = new GZipInputStream(await response.Content.ReadAsStreamAsync());
            responseBody = new StreamReader(inputStream).ReadToEnd();
        }
        else
        {
            responseBody = await response.Content.ReadAsStringAsync();

        }
        return responseBody;
    }

    /// <summary>
    /// 使用get方法异步请求
    /// </summary>
    /// <param name="url">目标链接</param>
    /// <returns>返回的字符串</returns>
    public static async Task<string> GetAsync(string url, Dictionary<string, string> header = null, bool Gzip = false)
    {

        HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false });
        if (header != null)
        {
            client.DefaultRequestHeaders.Clear();
            foreach (var item in header)
            {
                client.DefaultRequestHeaders.Add(item.Key, item.Value);
            }
        }
        HttpResponseMessage response = await client.GetAsync(url);
        response.EnsureSuccessStatusCode();//用来抛异常的
        string responseBody = "";
        if (Gzip)
        {
            GZipInputStream inputStream = new GZipInputStream(await response.Content.ReadAsStreamAsync());
            responseBody = new StreamReader(inputStream).ReadToEnd();
        }
        else
        {
            responseBody = await response.Content.ReadAsStringAsync();

        }
        return responseBody;
    }

    /// <summary>
    /// 使用post返回异步请求直接返回对象
    /// </summary>
    /// <typeparam name="T">返回对象类型</typeparam>
    /// <typeparam name="T2">请求对象类型</typeparam>
    /// <param name="url">请求链接</param>
    /// <param name="obj">请求对象数据</param>
    /// <returns>请求返回的目标对象</returns>
    public static async Task<T> PostObjectAsync<T, T2>(string url, T2 obj)
    {
        String json = JsonConvert.SerializeObject(obj);
        string responseBody = await PostAsyncJson(url, json); //请求当前账户的信息
        return JsonConvert.DeserializeObject<T>(responseBody);//把收到的字符串序列化
    }

    /// <summary>
    /// 使用Get返回异步请求直接返回对象
    /// </summary>
    /// <typeparam name="T">请求对象类型</typeparam>
    /// <param name="url">请求链接</param>
    /// <returns>返回请求的对象</returns>
    public static async Task<T> GetObjectAsync<T>(string url)
    {
        string responseBody = await GetAsync(url); //请求当前账户的信息
        return JsonConvert.DeserializeObject<T>(responseBody);//把收到的字符串序列化
    }
}

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 以下是一个简单的Python异步HTTP请求封装示例: ```python import asyncio import aiohttp class AsyncHttpRequest: def __init__(self, headers=None, timeout=None): self.headers = headers self.timeout = timeout async def get(self, url, params=None): async with aiohttp.ClientSession(headers=self.headers, timeout=self.timeout) as session: async with session.get(url, params=params) as response: return await response.text() async def post(self, url, data=None, json=None): async with aiohttp.ClientSession(headers=self.headers, timeout=self.timeout) as session: async with session.post(url, data=data, json=json) as response: return await response.text() ``` 该使用Python的asyncio库和aiohttp库来实现异步HTTP请求。它具有get和post方法来执行GET和POST请求。可以通过headers和timeout参数设置请求的头信息和超时时间。 在调用该时,可以使用await关键字来等待请求返回结果,如下所示: ```python async def main(): request = AsyncHttpRequest(headers={'User-Agent': 'Mozilla/5.0'}, timeout=10) response = await request.get('https://www.example.com') print(response) asyncio.run(main()) ``` 在此示例中,创建了一个AsyncHttpRequest对象,并使用get方法执行了一个GET请求。使用await关键字等待请求返回结果后,将响应文本打印到控制台上。 ### 回答2: Python中可以使用第三方库asyncio和aiohttp来封装异步http请求。 首先,我们需要导入相应的库: ```python import asyncio import aiohttp ``` 然后,我们可以定义一个异步http请求,如下所示: ```python class AsyncHttpRequest: def __init__(self): self.session = aiohttp.ClientSession() async def request(self, method, url, headers=None, params=None, data=None): async with self.session.request(method, url, headers=headers, params=params, data=data) as response: return await response.text() async def close(self): await self.session.close() ``` 在的初始化方法中,我们创建了一个aiohttp的ClientSession对象用于发送http请求。然后,定义了一个request方法来发送http请求并返回响应结果。在请求方法中,我们使用async with语句来发送请求,并使用asyncio库的await方法等待响应结果。最后,我们定义了一个close方法来关闭http请求的会话。 使用该异步http请求的例子如下: ```python async def main(): async_http_request = AsyncHttpRequest() response = await async_http_request.request('GET', 'https://www.example.com') print(response) await async_http_request.close() asyncio.run(main()) ``` 在主函数main中,我们创建了AsyncHttpRequest对象,并调用request方法发送了一个GET请求并获取了响应结果。最后,我们调用close方法关闭了http请求的会话。 以上就是使用asyncio和aiohttp封装异步http请求的简单示例。通过异步http请求,我们可以方便地发送异步请求并处理响应结果。 ### 回答3: Python中有多种方式可以封装异步http请求,如使用asyncio库、aiohttp库等。这里以aiohttp为例进行说明。 首先,我们可以定义一个HttpClient封装异步http请求的功能。该需要引入aiohttp库并使用async关键字来定义异步函数。 首先,在的初始化方法中,我们可以创建一个aiohttp的ClientSession对象作为的成员变量,以便在整个中进行http请求。 接下来,我们可以定义一个异步的GET请求方法,该方法接收一个url参数,并使用aiohttp库的get方法来发送异步的GET请求。我们可以使用await关键字来等待该请求的响应并返回结果。 然后,我们可以定义一个异步的POST请求方法,该方法接收一个url和data参数,使用aiohttp库的post方法来发送异步的POST请求。同样,我们也使用await关键字来等待该请求的响应并返回结果。 最后,我们需要在HttpClient中定义一个关闭方法,用于在使用完毕后关闭aiohttp的ClientSession对象,以释放资源。 总结来说,封装异步http请求主要包括以下步骤: 1. 引入aiohttp库和其他必要的库; 2. 创建并初始化的成员变量; 3. 定义异步的GET请求方法,接收url参数,使用aiohttp库发送异步GET请求并等待响应; 4. 定义异步的POST请求方法,接收url和data参数,使用aiohttp库发送异步POST请求并等待响应; 5. 定义关闭方法,用于关闭aiohttp的ClientSession对象。 通过以上步骤,我们可以封装一个简单的异步http请求,方便在Python中进行异步http请求的操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值