NETCORE - 调用第三方接口
NETCORE - 调用第三方接口
调用方式: WebApi
创建两个 NetCore WebApi 项目 ,框架:.net5
1) 项目:NETCORE.ConSul
2) 项目:NETCORE.ConSul.Service
一. HTTPClient方式
需要 引用包
System.Net.Http
a. 注入方式
一. 项目 NETCORE.ConSul.Service
1. 新建接口
namespace NETCORE.Consul.Service.Controllers { [Route("api/[controller]")] [ApiController] public class PenController : ControllerBase { //测试接口 [Route("GetPenInfo")] [HttpGet] public string GetPenInfo() { Task.Run(() => { Console.WriteLine($" get a new pen , Host: {0}", HttpContext.Request.Host.Value); }); return "success! get a new pen !"; } } }
2. 修改IP地址与端口:
路径:Properties / launchSettings.json
{ "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:24384", "sslPort": 44335 } }, "$schema": "http://json.schemastore.org/launchsettings.json", "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "launchUrl": "swagger", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "NETCORE.Consul.Service": { "commandName": "Project", "launchBrowser": true, "launchUrl": "swagger", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, "dotnetRunMessages": "true", "applicationUrl": "https://10.10.50.99:5055;http://10.10.50.99:5056", "jsWebView2Debugging": true } } }
3. 调试
接口访问地址:https://10.10.50.99:5055/api/Pen/GetPenInfo
二. 项目 NETCORE.Consul
1. 修改IP地址与端口:
路径:Properties / launchSettings.json
{ "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://10.10.50.99:19691", "sslPort": 44328 } }, "$schema": "http://json.schemastore.org/launchsettings.json", "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "launchUrl": "swagger", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "NETCORE.ConSul": { "commandName": "Project", "launchBrowser": true, "launchUrl": "swagger", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, "dotnetRunMessages": "true", "applicationUrl": "https://10.10.50.99:5001;http://10.10.50.99:5000" } } }
2. 注入 HTTPClient
在 startup.cs 中修改 ConfigureServices 方法
public void ConfigureServices(IServiceCollection services) { //用于调用博客园接口 services.AddHttpClient("ServiceBlogs", x => { x.BaseAddress = new Uri("https://www.cnblogs.com"); x.DefaultRequestHeaders.Add("Cache-Control", "no-cache"); }); //用于调用Service1接口 services.AddHttpClient("ServiceService1", x => { x.BaseAddress = new Uri("https://10.10.50.99:5055"); x.DefaultRequestHeaders.Add("Cache-Control", "no-cache"); }).ConfigurePrimaryHttpMessageHandler(() =>//防止报ssl错误 { return new HttpClientHandler() { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator }; });
services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "NETCORE.ConSul", Version = "v1" }); }); }
3. 新增接口
namespace NETCORE.ConSul.Controllers { [Route("api/[controller]")] [ApiController] public class BookController : ControllerBase { IHttpClientFactory _clientFactory; public BookController(IHttpClientFactory clientFactory) { _clientFactory = clientFactory; } [Route("CallPen")] [HttpPost] public async Task<IActionResult> CallPen() { var client = _clientFactory.CreateClient("ServiceService1");//必须与startup里面注入的名称对应 //var content = new StringContent(""); //content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); var response = await client.GetAsync("api/pen/GetPenInfo"); var sss = response.Content.ReadAsStringAsync().Result; return Ok(sss); } } }
4. 调用接口
b. 直接调用方式
private async Task<string> TrunsOtherService(string url, FormUrlEncodedContent formContent, string method) { var res = ""; HttpResponseMessage response = null; using (HttpClient httpClient = new HttpClient()) { var requestUri = url; if (method == "put") response = await httpClient.PutAsync(url, formContent); if (method == "post") response = await httpClient.PostAsync(url, formContent); res = response.Content.ReadAsStringAsync().Result; Console.WriteLine(res); } return res; }
public class ClientService { private readonly HttpClient client; public ClientService() { client = new HttpClient(); } public async Task<string> GetString(string baseUrl, Dictionary<string, string> parameters) { var queryString = new FormUrlEncodedContent(parameters); var requestUri = new Uri(baseUrl + "?" + queryString.ReadAsStringAsync().Result); try { HttpResponseMessage response = await client.GetAsync(requestUri); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); return responseBody; } catch (HttpRequestException e) { throw e; } } public async Task<T> PostClient<T>(string baseUrl, object JsonData) { // 序列化字符串列表为JSON字符串 string jsonContent = JsonSerializer.Serialize(JsonData); StringContent content = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync(baseUrl, content); response.EnsureSuccessStatusCode(); string responseContent = await response.Content.ReadAsStringAsync(); var outputList = JsonSerializer.Deserialize<T>(responseContent); return outputList; } catch (HttpRequestException e) { throw e; } } }
二. HttpWebRequest 方式
webapi 接口:
/// <summary> /// 保存Json文件 /// </summary> /// <returns></returns> [HttpPost] [Route("SaveJson")] public async Task<ActionResult> SaveJsonAsync([FromBody] string str) { try { var res = (new CDEService()).WriteJson(str); return Ok(res); } catch (Exception ex) { return BadRequest(ex.Message + ex.InnerException?.Message); } }
接口调用:
/// <summary> /// 测试Json文件 /// </summary> /// <returns></returns> [HttpPost] [Route("TestAsync")] public async Task<ActionResult> TestAsync([FromBody] string str) { try { string url = "https://localhost:7096/api/ACAD/SaveJson"; Encoding encoding = Encoding.UTF8; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.Accept = "text/html, application/xhtml+xml, */*"; //这里只有使用var data = HttpContext.Current.Request.Form["Name"].ToString();才切换到表单 //如果api使用Request.Content.ReadAsStringAsync();则无所谓切换 //request.ContentType = "application/x-www-form-urlencoded ";//根据服务端进行 切换 request.ContentType = "application/json; charset=utf-8 "; string data = JsonConvert.SerializeObject(str); byte[] buffer = encoding.GetBytes(data); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { var ssss = reader.ReadToEnd(); } return Ok("ok"); } catch (Exception ex) { return BadRequest(ex.Message + ex.InnerException?.Message); } }
项目:NETCORE.ConSul
项目:NETCORE.ConSulService
附代码:https://gitee.com/wuxincaicai/NETCORE.git