首页 .NET/Web NETCoreAPI调用WebService接口

NETCoreAPI调用WebService接口

作者:胡同里的砖头 围观群众:252 更新于:2023-07-25

1.在Startup.cs的ConfigureServices方法内添加注入这个HttpClient 这个内置对象

services.AddHttpClient();

2.创建一个控制器,然后注入这个对象
readonly IHttpClientFactory _httpClientFactory;

/// <summary>
/// 通过构造函数实现注入
/// </summary>
/// <param name="httpClientFactory"></param>
public TestController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}

3.封装一个调用接口的方法
    /// <summary>
/// 封装使用HttpClient调用WebService
/// </summary>
/// <param name="url">URL地址</param>
/// <param name="content">参数</param>
/// <returns></returns>
private async Task<string> PostHelper(string url, HttpContent content)
{
var result = string.Empty;
try
{
using (var client = _httpClientFactory.CreateClient())
using (var response = await client.PostAsync(url, content))
{
if (response.StatusCode == HttpStatusCode.OK)
{
result = await response.Content.ReadAsStringAsync();
XmlDocument doc = new XmlDocument();
doc.LoadXml(result);
result = doc.InnerText;
}
}
}
catch (Exception ex)
{
result = ex.Message;
}
return result;
}

4.调用接口
 [HttpPost]
public async Task<string> selectcityPost(string byProvinceName)
{
string strResult = "";
try
{
// url地址格式:WebService地址+方法名称
// WebService地址:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx
// 方法名称: getSupportCity
string url = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getSupportCity";
// 参数
Dictionary<string, string> dicParam = new Dictionary<string, string>();
//参数名
dicParam.Add("byProvinceName", byProvinceName);
// 将参数转化为HttpContent
HttpContent content = new FormUrlEncodedContent(dicParam);
strResult = await PostHelper(url, content);
}
catch (Exception ex)
{
strResult = ex.Message;
}

return strResult;
}

然后运行结果

  • 本文标题: NETCoreAPI调用WebService接口
  • 文章分类:【.NET/Web】
  • 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.
留言评论
站点声明:
1、本站【胡同里的砖头】个人博客,借鉴网上一些博客模板,取其各优点模块自行拼装开发,本博客开发纯属个人爱好。
2、所有笔记提供给广大用户交流使用,可转载,可复制,纯个人开发所遇问题锦集记录使用
Copyright © huzlblog.com All Rights Reserved. 备案号:苏ICP备2021056683号-8