环境搭建
服务注册
builder.Services.AddHttpClient();
创建实体类
namespace HttpClient
{
public class RequestModel
{
public string userName { set; get; }
public string password { set; get; }
}
public class ApiResult
{
bool IsSuccess { set; get; }
object Result { set; get; }
string Msg { set; get; }
}
}
创建服务提供类
using Microsoft.AspNetCore.Mvc;
namespace HttpClient.Controllers
{
[ApiController]
[Route("[controller]/[action]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger _logger;
public WeatherForecastController(ILogger logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
[HttpPost]
public object Post([FromBody] RequestModel model)
{
return model;
}
}
}
测试
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Text;
using System.Text.Json;
using static System.Net.Mime.MediaTypeNames;
namespace HttpClient.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class Demo : ControllerBase
{
private readonly IHttpClientFactory _httpClientFactory;
public Demo(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
[HttpPost]
public async Task Post()
{
RequestModel req = new RequestModel
{
userName = "zhangsan",
password = "password",
};
// 包装参数
StringContent stringContent = new StringContent(
JsonSerializer.Serialize(req),
Encoding.UTF8,
Application.Json
);
System.Net.Http.HttpClient httpClient = _httpClientFactory.CreateClient();
using var response = await httpClient.PostAsync("https://localhost:7038/WeatherForecast/Post", stringContent);
var task = response.Content.ReadAsStringAsync();
return await task;
}
[HttpGet]
public async Task Get()
{
HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://localhost:7038/WeatherForecast/Get")
{
Headers =
{
// 设置请求头
}
};
var client = _httpClientFactory.CreateClient();
HttpResponseMessage httpResponseMessage = client.Send(httpRequestMessage);
if (httpResponseMessage.IsSuccessStatusCode)
{
var result = await httpResponseMessage.Content.ReadAsStringAsync();
return result;
}
else
{
return "请求失败";
}
}
}
}