背景介绍
http://www.webxml.com.cn/WebServices/WeatherWebService.asmx
在这个公开的Webservice上,我想使用getSupportCity这个功能
解决方案
using RestSharp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace WebserviceDemo2
{public partial class Form1 : Form{public Form1(){InitializeComponent();}public static async Task<string> CallGetSupportCityAsync(){try{var client = new RestClient("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx");var request = new RestRequest("getSupportCity", Method.Get);request.AddParameter("byProvinceName", "ALL", ParameterType.QueryString); // 使用查询参数 // 设置一个合理的超时值(例如5秒) request.Timeout = 50000;// 你可以在这里添加其他通用的请求头部 request.AddHeaders(new Dictionary<string, string>{{ "Accept", "*/*" },{ "Host", "www.webxml.com.cn" },{ "Connection", "keep-alive" },});// 执行请求并获取响应 var response = await client.ExecuteAsync(request); // 注意这里使用了异步方法 // 输出响应内容 return response.Content.ToString();}catch (Exception ex){// 处理异常 Console.WriteLine("发生错误: " + ex.Message);return null;}return null;}private async void button1_Click(object sender, EventArgs e){string response = await CallGetSupportCityAsync();MessageBox.Show(response);}}
}