当前位置: 首页 > news >正文

C# 调用Webservice接口接受数据测试

1.http://t.csdnimg.cn/96m2g

此链接提供测试代码;

2.http://t.csdnimg.cn/64iCC

此链接提供测试接口;

关于Webservice的基础部分不做赘述,下面贴上我的测试代码(属于动态调用Webservice):

1:http助手类

using System.Net;
using System.Text;
using System.Web;
using static System.Net.Mime.MediaTypeNames;namespace WebServiceGetWeather;public class HttpHelper
{private static HttpHelper m_Helper;/// <summary>/// 单例模式/// </summary>public static HttpHelper Helper{get { return m_Helper ?? (m_Helper = new HttpHelper()); }}/// <summary>/// 获取请求的数据/// </summary>/// <param name="strUrl">请求地址</param>/// <param name="requestMode">请求方式</param>/// <param name="parameters">参数</param>/// <param name="requestCoding">请求编码</param>/// <param name="responseCoding">响应编码</param>/// <param name="timeout">请求超时时间(毫秒)</param>/// <returns>请求成功响应信息,失败返回null</returns>public string GetResponseString(string strUrl, ERequestMode requestMode,  Dictionary<string,string> parameters, Encoding requestCoding, Encoding responseCoding, int timeout = 300){string url = VerifyUrl(strUrl);HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));HttpWebResponse webResponse = null;switch (requestMode){case ERequestMode.Get:webResponse = GetRequest(webRequest, timeout);break;case ERequestMode.Post:webResponse = PostRequest(webRequest, parameters, timeout, requestCoding);break;}if (webResponse != null && webResponse.StatusCode == HttpStatusCode.OK){using (Stream newStream = webResponse.GetResponseStream()){if (newStream != null)using (StreamReader reader = new StreamReader(newStream, responseCoding)){string result = reader.ReadToEnd();return result;}}}return null;}/// <summary>/// get 请求指定地址返回响应数据/// </summary>/// <param name="webRequest">请求</param>/// <param name="timeout">请求超时时间(毫秒)</param>/// <returns>返回:响应信息</returns>private HttpWebResponse GetRequest(HttpWebRequest webRequest, int timeout){try{webRequest.Accept = "text/html, application/xhtml+xml, application/json, text/javascript, */*; q=0.01";webRequest.Headers.Add("Accept-Language", "zh-cn,en-US,en;q=0.5");webRequest.Headers.Add("Cache-Control", "no-cache");webRequest.UserAgent = "DefaultUserAgent";//webRequest.ContentType = "application / json";webRequest.Timeout = timeout;webRequest.Method = "GET";// 接收返回信息HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();return webResponse;}catch (Exception ex){return null;}}/// <summary>/// post 请求指定地址返回响应数据/// </summary>/// <param name="webRequest">请求</param>/// <param name="parameters">传入参数</param>/// <param name="timeout">请求超时时间(毫秒)</param>/// <param name="requestCoding">请求编码</param>/// <returns>返回:响应信息</returns>private HttpWebResponse PostRequest(HttpWebRequest webRequest, Dictionary<string, string> parameters, int timeout, Encoding requestCoding){try{// 拼接参数string postStr = string.Empty;if (parameters != null){parameters.All(o =>{if (string.IsNullOrEmpty(postStr))postStr = string.Format("{0}={1}", HttpUtility.UrlEncode(o.Key), HttpUtility.UrlEncode(o.Value));elsepostStr += string.Format("&{0}={1}", HttpUtility.UrlEncode(o.Key), HttpUtility.UrlEncode(o.Value));return true;});}byte[] byteArray = requestCoding.GetBytes(postStr);webRequest.Accept = "text/html, application/xhtml+xml, application/json, text/javascript, */*; q=0.01";webRequest.Headers.Add("Accept-Language", "zh-cn,en-US,en;q=0.5");webRequest.Headers.Add("Cache-Control", "no-cache");webRequest.UserAgent = "DefaultUserAgent";//webRequest.Timeout = timeout;webRequest.ContentType = "application/x-www-form-urlencoded";webRequest.ContentLength = byteArray.Length;webRequest.Method = "POST";// 将参数写入流using (Stream newStream = webRequest.GetRequestStream()){newStream.Write(byteArray, 0, byteArray.Length);newStream.Close();}// 接收返回信息HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();return webResponse;}catch (Exception ex){return null;}}/// <summary>/// 验证URL/// </summary>/// <param name="url">待验证 URL</param>/// <returns></returns>private string VerifyUrl(string url){if (string.IsNullOrEmpty(url))throw new Exception("URL 地址不可以为空!");if (url.StartsWith("http://", StringComparison.CurrentCultureIgnoreCase))return url;return string.Format("http://{0}", url);}
}
public enum ERequestMode
{Get,Post
}

2:调用方法

internal class Program{static void Main(string[] args){Console.WriteLine("Hello, World!");TestInvoke();}/// <summary>/// 测试调用/// </summary>static void TestInvoke(){//组织参数//<参数名,参数值>Dictionary<string, string> parameters = new Dictionary<string, string>();parameters.Add("byProvinceName", "北京");//getSupportCity是方法名称直接放在后面string url = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getSupportCity ";string _result = HttpHelper.Helper.GetResponseString(url, ERequestMode.Post, parameters, Encoding.Default, Encoding.UTF8);}

注意事项:

1:接口方法里面的案例参数要与代码中指定的一致:

 2:方法名直接放在url结尾:

string url = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getSupportCity ";

△   其中getSupportCity 就是方法名。

Dictionary<string, string> parameters = new Dictionary<string, string>();

△   其中parameters 的key是方法参数名,value是参数值。

先装一下原创,原作有想法评论或者私聊,即可更改。

http://www.lryc.cn/news/411190.html

相关文章:

  • 工作流流程引擎框架推荐来了
  • 从技术博客到个人 IP 矩阵:全面攻略与实战示例
  • SOFAJRaft 简介
  • c#中Oracle.DataAccess.dll连接数据库的报错处理
  • PyCharm2024 专业版激活设置中文
  • 视觉SLAM第一讲
  • 吴恩达机器学习C1W2Lab05-使用Scikit-Learn进行线性回归
  • springboot集成thymeleaf实战
  • SpringBoot+Vue+kkFileView实现文档管理(文档上传、下载、在线预览)
  • 从代码层面熟悉UniAD,开始学习了解端到端整体架构
  • 微信小程序-选中文本时选中checkbox
  • [玄机]流量特征分析-蚁剑流量分析
  • 2-51 基于matlab的IFP_FCM(Improved fuzzy partitions-FCM)
  • Java人力资源招聘社会校招类型招聘小程序
  • oracle表、表空间使用空间
  • IDEA管理远程仓库Git
  • 【数据结构】Java实现二叉搜索树
  • 钉钉小程序如何通过setdate重置对象
  • DjangoRF-10-过滤-django-filter
  • Android SurfaceFlinger——GraphicBuffer的生成(三十二)
  • <数据集>棉花识别数据集<目标检测>
  • [240730] OpenAI 推出基于规则的奖励机制 (RBR) 提升模型安全性 | 英特尔承认其13、14代 CPU 存在问题
  • 【JavaScript】展开运算符详解
  • 麒麟V10系统统一认证子系统国际化
  • C语言进阶 13. 文件
  • LinuxCentos中ELK日志分析系统的部署(详细教程8K字)附图片
  • Vscode ssh Could not establish connection to
  • 数字陷波器的设计和仿真(Matlab+C)
  • [玄机]流量特征分析-常见攻击事件 tomcat
  • 【TOOLS】Project 2 Maven Central