.net core 使用http post调用第三方接口

第一种方式 application/json

ContentType类型为application/json

在这里介绍使用 IHttpClientFactory 方式调用第三方接口,

使用方法很简单,

直接上代码。

首先注入全局变量

private readonly IHttpClientFactory _httpClientFactory;

/// <summary>
/// http post请求
/// </summary>
/// <param name="requestUri">地址</param>
/// <param name="parameter">入参</param>
/// <param name="token"></param>
/// <param name="headers">头信息</param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
private async Task<string> PostAsync(string requestUri, string parameter, string token, Dictionary<string, string> headers)
{
    try
    {
        var client = _httpClientFactory.CreateClient();
        var content = new StringContent(parameter, Encoding.UTF8, "application/json");
        // 添加token到请求头中
        if (token != null)
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        }
        foreach (var header in headers)
        {
            client.DefaultRequestHeaders.Add(header.Key, header.Value);
        }
        var response = await client.PostAsync(requestUri, content);
        string statusCode = ((int)response.StatusCode).ToString();
        response.EnsureSuccessStatusCode();
        string resultMsg = await response.Content.ReadAsStringAsync();
        _logger.LogWarning($"返回结果:{resultMsg},入参:{parameter}");
        return resultMsg;
        //result = JsonConvert.DeserializeObject<Result>(resultMsg);
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message, ex);
    }
}

其中,

paremer为入参实体类

requestUri为接口地址

_authorization为token值,也可以写到DefaultRequestHeaders中

第二种方式 application/x-www-form-urlencoded

ContentType类型为application/x-www-form-urlencoded

1 入参为字典类型
private async Task<string> Post2Async(string requestUri, Dictionary<string, string> parameter, string token, Dictionary<string, string> headers)
{
    try
    {
        var client = _httpClientFactory.CreateClient();
        var content = new FormUrlEncodedContent(parameter);
        // 添加token到请求头中
        if (token != null)
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        }
        foreach (var header in headers)
        {
            client.DefaultRequestHeaders.Add(header.Key, header.Value);
        }
        var response = await client.PostAsync(requestUri, content);
        string statusCode = ((int)response.StatusCode).ToString();
        response.EnsureSuccessStatusCode();
        string resultMsg = await response.Content.ReadAsStringAsync();
        _logger.LogWarning($"返回结果:{resultMsg},入参:{parameter.ToJsonString()}");
        return resultMsg;
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message, ex);
    }
}

这种方法的入参格式为字典类型,以下为调用示例:

var path = "/api/ec/dev/message/sendCustomMessageSingle";
var token = await GetTokenAsync();
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("token", token);
headers.Add("appid", _appid);
//headers.Add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
headers.Add("skipsession", "1");

//var parameter = JsonConvert.SerializeObject(content);
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add(nameof(content.code), content.code);
data.Add(nameof(content.userIdList), content.userIdList);
data.Add(nameof(content.creater), content.creater);
data.Add(nameof(content.title), content.title);
data.Add(nameof(content.context), content.context);
var resultMsg = await Post2Async(_ip + path, data,"", headers);
2 入参为字符串
private async Task<string> Post3Async(string url, string parameter, Dictionary<string, string> headers)
{
    using (var client = new HttpClient())
    {
        //var data = new StringContent("param1=value1&param2=value2", Encoding.UTF8, "application/x-www-form-urlencoded");
        var data = new StringContent(parameter, Encoding.UTF8, "application/x-www-form-urlencoded");
        _logger.LogWarning($"data:{data.ToJsonString()};parameter:{parameter}");
        // 添加header参数
        //client.DefaultRequestHeaders.Add("Authorization", "Bearer your_token_here");
        foreach (var header in headers)
        {
            client.DefaultRequestHeaders.Add(header.Key, header.Value);
        }
        _logger.LogWarning($"header:{client.DefaultRequestHeaders.ToJsonString()}");

        try
        {
            var response = await client.PostAsync(url, data);
            response.EnsureSuccessStatusCode();

            var responseBody = await response.Content.ReadAsStringAsync();
            return responseBody;
        }
        catch (HttpRequestException e)
        {
            throw new Exception(e.Message);
        }
    }
}

这种方法的入参格式为 param1=value1&param2=value2

以下为调用示例:

var path = "/api/ec/dev/message/sendCustomMessageSingle";
var token = await GetTokenAsync();
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("token", token);
headers.Add("appid", _appid);
//headers.Add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
headers.Add("skipsession", "1");

var data = $"code={content.code}&userIdList={content.userIdList}&creater={content.creater}&title={content.title}&context={content.context}";
var resultMsg = await Post3Async(_ip + path, data, headers);

异常信息

调用第三方接口如果报一下异常

Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.

译文

标题名称被滥用。确保请求标头与HttpRequestMessage一起使用,响应标头与HttpResponseMessage一起使用以及内容标头与HttpContent对象一起使用。

出现上述异常信息基本上是请求头出现问题,在请求头里加上这个headers.Add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");就会报上面异常,本地可以调试的话很容易发现问题,如果本地不能调的话,可以加日志监控请求头信息,也可以快速发现问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一个程序员_zhangzhen

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

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

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

打赏作者

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

抵扣说明:

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

余额充值