首页 > 编程语言 >.Net(C#)后台发送Get和Post请求的几种方法总结

.Net(C#)后台发送Get和Post请求的几种方法总结

时间:2023-02-08 15:55:13浏览次数:49  
标签:Get C# await responseBody client new Net response HttpClient

1、每次请求使用HttpClient单例

private static readonly Lazy<HttpClient> lazy = new Lazy<HttpClient>(() => new HttpClient());
public static HttpClient Instance { get { return lazy.Value; } }
private HttpClient getConnection(int timeout,string baseAddress)
{
    Instance.Timeout = System.TimeSpan.FromMilliseconds(timeout);
    //client.MaxResponseContentBufferSize = 500000;
    Instance.BaseAddress = new Uri(baseAddress);
    return Instance; ;
}

HttpClient应该只被实例化一次,并在应用程序的整个生命周期中被重用。如为每个请求实例化一个HttpClient类将耗尽沉重负载下可用的套接字数量。这将导致SocketException错误。下面是正确使用HttpClient的示例。

// HttpClient是为每个应用程序实例化一次,而不是每次请求创建一个实例
static readonly HttpClient client = new HttpClient();
static async Task Main()
{
  // 在try/catch块中调用异步网络方法来处理异常。
  try	
  {
     HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
     response.EnsureSuccessStatusCode();
     string responseBody = await response.Content.ReadAsStringAsync();
     // string responseBody = await client.GetStringAsync(uri);
     Console.WriteLine(responseBody);
  }  
  catch(HttpRequestException e)
  {
     Console.WriteLine("\nException Caught!");	
     Console.WriteLine("Message :{0} ",e.Message);
  }
}

2、通过HttpClient发送Get和Post请求

HttpClient推荐使用单一实例共享使用,发关请求的方法推荐使用异步的方式,代码如下,

private static readonly HttpClient client = new HttpClient();
//发送Get请求
var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");
//发送Post请求
var values = new Dictionary
{
   { "thing1", "hello" },
   { "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();

3、封装

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);//把收到的字符串序列化
    }
}

4、配置Proxy(代理)执行Get和Post请求数据操作

using System.Net;
using System.Net.Http;
var builder = new ConfigurationBuilder()
	 .SetBasePath(Directory.GetCurrentDirectory())
	 .AddJsonFile("appsettings.json");
var configuration = builder.Build();
var webProxy = new WebProxy(
	 new Uri(configuration["ProxyUri"]), 
	 BypassOnLocal: false);
var proxyHttpClientHandler = new HttpClientHandler {
	 Proxy = webProxy,
	 UseProxy = true,
};
var client = new HttpClient(proxyHttpClientHandler) {
	 BaseAddress = new Uri(configuration["RestServiceUri"])
};
//发送Get请求
var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");
//发送Post请求
var values = new Dictionary
{
   { "thing1", "hello" },
   { "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();

配置文件

/* appsettings.json */
{
    "RestServiceUri": "http://192.168.31.11:5001/api",
    "ProxyUri": "http://192.168.31.11:8080"
}

标签:Get,C#,await,responseBody,client,new,Net,response,HttpClient
From: https://www.cnblogs.com/shenghuotaiai/p/17102005.html

相关文章