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));
					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是参数值。

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

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值