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

news2024/9/17 8:21:45

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));
					else
						postStr += 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.coloradmin.cn/o/1960808.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Appium自动化测试 ------ 常见模拟操作!

Appium自动化测试中的常见模拟操作涵盖了多种用户交互行为&#xff0c;这些操作对于自动化测试框架来说至关重要&#xff0c;因为它们能够模拟真实用户的使用场景&#xff0c;从而验证应用程序的功能和稳定性。 以下是一些Appium自动化测试中常见的模拟操作&#xff1a; 基本操…

XPathParser类

XPathParser类是mybatis对 javax.xml.xpath.XPath的包装类。 接下来我们来看下XPathParser类的结构 1、属性 // 存放读取到的整个XML文档private final Document document;// 是否开启验证private boolean validation;// 自定义的DTD约束文件实体解析器&#xff0c;与valida…

JavaSE面向对象进阶

static 介绍 static表示静态&#xff0c;是Java中的一个修饰符可以修饰成员方法、成员变量 被static修饰的成员变量&#xff0c;叫做静态变量被static修饰的成员方法&#xff0c;叫做静态方法 静态变量 特点&#xff1a;被该类所有对象共享 调用方式&#xff1a; 类名调用&am…

关于@Async

Spring Boot 2.x 开始&#xff0c;默认情况下&#xff0c;Spring AOP 使用 CGLIB 代理 Async不能在同一个类中直接调用 关于在控制器不能使用Async 并不是因为SpringBoot2以前使用JDK代理 因为JDK代理需要类实现接口,控制器没有实现接口等原因 真正原因是 Async 不能…

windows@powershell@任务计划@自动任务计划@taskschd.msc.md

文章目录 使用任务计划windows中的任务计划任务计划命令行程序开发windows 应用中相关api传统图形界面FAQ schtasks 命令常见用法创建计划任务删除计划任务查询计划任务修改计划任务运行计划任务 PowerShell ScheduledTasks常用 cmdlet 简介1. Get-ScheduledTask2. Register-Sc…

手动在ubuntu上搭建一个nginx,并安装证书的最简化完整过程

背景&#xff1a;由于想做个测试&#xff1a;即IP为A的服务器&#xff0c;绑定完域名X后&#xff0c;如果再绑定域名Y&#xff0c;能不能被访问到。&#xff08;假设对A不做绑定域名的设置&#xff09; 这个问题的来源&#xff0c;见上一篇文章&#xff1a;《云服务器被非法域名…

kaggle使用api下载数据集

背景 kaggle通过api并配置代理下载数据集datasets 步骤 获取api key 登录kaggle&#xff0c;点个人资料&#xff0c;获取到自己的api key 创建好的key会自动下载 将key放至家目录下的kaggle.json文件中 我这里是windows的administrator用户。 装包 我用了虚拟环境 pip …

021.自定义指纹浏览器编译-修改ClientRects指纹

一、什么是ClientRects指纹 ClientRects指纹获取的核心方法是DOM元素方法getClientRects()​ 。getClientRects()​ 可以返回一个元素的所有 CSS 边界框&#xff08;ClientRect对象数组&#xff09;&#xff0c;包括其大小、位置等信息。每个边界框由其左上角的 x, y 坐标和宽…

基于YOLOv10深度学习的商品条形码智能检测与识别系统【python源码+Pyqt5界面+数据集+训练代码】深度学习实战、目标检测

《博主简介》 小伙伴们好&#xff0c;我是阿旭。专注于人工智能、AIGC、python、计算机视觉相关分享研究。 ✌更多学习资源&#xff0c;可关注公-仲-hao:【阿旭算法与机器学习】&#xff0c;共同学习交流~ &#x1f44d;感谢小伙伴们点赞、关注&#xff01; 《------往期经典推…

小程序、H5、APP中的微信支付概述和实战总结

最近开发的一个微信小程序的项目结束了&#xff0c;里面用到了支付相关的api&#xff0c;借着项目总结一下小程序各种场景支付的逻辑。 1. 微信支付概述 1.1 微信支付的重要性 微信支付作为中国领先的移动支付方式之一&#xff0c;其便捷性、安全性以及广泛的用户基础使其成为…

已解决丨怎么快速的让IP地址实现HTTPS访问?

要快速让IP地址实现HTTPS访问&#xff0c;可以遵循以下简洁步骤&#xff1a; 1. 确认公网IP地址 确保你拥有一个固定的公网IP地址&#xff0c;因为HTTPS访问需要通过互联网上的公网IP进行。 2. 选择证书颁发机构&#xff08;CA&#xff09; 选择一个受信任的证书颁发机构&a…

从PLC到云端,ZP3000系列网关助力工业数字化转型

ZP3000系列远程控制网关是一款专为满足现代工业自动化和远程监控需求而设计且功能强大的通讯模块。它的多接口设计和灵活配置能力&#xff0c;使得它能够适应多种复杂的工业通信和监控场景。以下是关于ZP3000系列远程控制网关的详细特点和应用场景&#xff1a; 产品特点 双以太…

playwright 模拟F11 全屏

直接上源代码 import multiprocessing import time from multiprocessing import Processfrom playwright.sync_api import sync_playwrightdef run(playwright):# 使用 Chromium 浏览器运行 设置 headlessFalse 以打开可视化窗口browser playwright.chromium.launch(headles…

C语言——设计TVM(地铁自动售票机)机软件。

输入站数&#xff0c;计算费用&#xff0c;计费规则&#xff0c;6站2元&#xff0c;7-10站3元&#xff0c;11站以上为4元。 输入钱数&#xff0c;计算找零(找零时优先找回面额大的钞票)&#xff0c;找零方式为各种面额张数&#xff0c;可识别面额&#xff1a; 100,50,20,10,5,1…

linux中mysql的安装使用(普通版版本+docker版本)

linux中mysql的安装使用 一、普通安装1.下载安装包2.流程 二、用docker安装1.拉取mysql镜像2.启动镜像3.开启权限第一种情况第二种情况 三、用Navicat连接 一、普通安装 1.下载安装包 挑选个你喜欢的目录&#xff0c;用wget下载并且解压 wget http://dev.mysql.com/get/Down…

指针!!C语言 字符串篇(第四篇)

目录 一. sizeof和strlen的对比 二. 数组和指针笔试题解析 2.1 一维数组 2.2 字符数组 2.3 二维数组 一. sizeof和strlen的对比 在C语言中有两个比较相似的知识点&#xff0c;就是sizeof和strlen&#xff0c;下面我们来讲一下它们两者之间有什么不同之处&#xff1f; &a…

python脚本制作循环执行命令行

python import subprocess import sysif __name____main__:ret 1while ret!0:ret subprocess.call(sys.argv[1:], textTrue)pack pip install pyinstaller pyinstaller --onefile loop.py pyinstaller -i *.ico loop.py #指定ico图标 使用场景 使用上面生成的loop.exe调用c…

前端开发者必备:揭秘谷歌F12调试的隐藏技巧!

前言 使用断点&#xff08;breakpoint&#xff09;是调试 JavaScript 代码的一种非常有效的方式。通过在代码的关键位置设置断点&#xff0c;可以阻止页面的状态变化&#xff0c;从而方便地检查和修改页面的当前状态。 1. 使用 setTimeout 配合 debugger 和 console.log setTi…

调用百度的大模型API接口实现AI对话!手把手教程!

本文介绍如何使用百度的大模型API接口实现一个AI对话项目 1 注册百度云 2 获取API接口 3 配置环境 4 代码编写与运行 5 chat models 1 注册百度云 搜索百度云&#xff0c;打开官网注册&#xff0c;充值一点点大米&#xff08;收费很低&#xff0c;大概生成几个句子花费一毛…

立仪光谱共焦传感器应用测量之:汽车连接器高度差测量

01 检测要求&#xff0c;要求测量汽车连接器的高度差 02 检测方式 根据观察&#xff0c;我们采用立仪科技光谱共焦H4UC控制器搭配D65A52系列镜头&#xff0c;角度最大&#xff0c;外径最大&#xff0c;量程大&#xff0c;可以有效应用于测量弧面&#xff0c;大角度面等零件。 0…