在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
C#是通过HttpWebRequest类和HttpWebResponseL类来实现http请求的发出和http响应的接收的,由于本人刚用这两个类,不是太熟悉,所以属性和方法就不在这里给大家讲解了。 代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Xml; using System.Web; using System.IO; using System.Runtime.Serialization.Json; using System.Runtime.Serialization; namespace httpTest { class Program { static void Main(string[] args) { Console.WriteLine("请输入您要查询的地区!"); string region = Console.ReadLine(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://api.36wu.com/Weather/GetWeather?district="+region); request.Method = "GET"; HttpWebResponse response = request.GetResponse() as HttpWebResponse; StreamReader stream = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string jsonstr = stream.ReadLine(); var ser = new DataContractJsonSerializer(typeof(weater)); var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonstr)); weater sn = (weater)ser.ReadObject(ms); Console.WriteLine("{0}的当前气温是{1}",region,sn.data.temp); Console.ReadKey(); //记得要关闭流 } } [DataContract] class weater { [DataMember] public int status { get; set; } [DataMember] public string message { get; set; } [DataMember] public data data { get; set; } } [DataContract] class data { [DataMember] public string dateTime { get; set; } [DataMember] public string city { get; set; } [DataMember] public string temp { get; set; } [DataMember] public string minTemp { get; set; } [DataMember] public string maxTemp { get; set; } [DataMember] public string weathe { get; set; } [DataMember] public string windDirection { get; set; } [DataMember] public string windForce { get; set; } [DataMember] public string humidity { get; set; } [DataMember] public string img_1 { get; set; } [DataMember] public string img_2 { get; set; } [DataMember] public string refreshTime { get; set; } } }
如果请求的字符串转json,可以用Newtonsoft.Json.dll 或 System.Text.Json
转: https://blog.csdn.net/green__apple/article/details/42292717 https://docs.microsoft.com/zh-cn/dotnet/framework/network-programming/how-to-request-data-using-the-webrequest-class https://docs.microsoft.com/zh-cn/dotnet/api/system.net.webrequest?view=net-5.0
|
请发表评论