栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

C# .Net获取SoJson实时天气接口的数据

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C# .Net获取SoJson实时天气接口的数据

C#实时天气接口

提示:可同步(后端直接请求)或异步(前端Ajax异步请求)请求,返回的是json格式的天气数据。
注意:服务器端必须要有互联网才能请求此接口。

目录
  • C#实时天气接口
  • 前言
  • 一、后端请求代码
  • 二、前端请求代码
  • 三、城市编码json


前言

提示:这是服务器端请求数据方式,前端请求可采用Ajax调用。

一、后端请求代码

说明:http://t.weather.itboy.net/api/weather/city/城市编码(如:101270101)为接口地址,该地址可能会变更,注意关注sojson官方天气接口的地址
sojson天气接口文档地址:https://www.sojson.com/blog/305.html

代码如下:

/// 
/// 根据城市编码获取天气json
/// 
/// 城市编码
/// 天气json
protected string GetWeatherByCity(string cityCode)
{
     try
     {
          string url = "http://t.weather.itboy.net/api/weather/city/" + cityCode;
          System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
          request.Timeout = 10000;
          request.UserAgent = "Code Sample Web Client";
          request.Credentials = CredentialCache.DefaultCredentials;
          //HttpWebRequest 对象 获取GetResponse 转换成HttpWebResponse
          System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse;
          //通过HttpWebResponse response.GetResponseStream()获取输出流
          System.IO.Stream str = response.GetResponseStream();
          System.IO.StreamReader reader = new System.IO.StreamReader(str, System.Text.Encoding.GetEncoding("utf-8"));
          string weathhtml = reader.ReadToEnd();
          str.Close();
          reader.Close();
          return weathhtml;
     }
     catch (Exception)
     {
          return "请求异常";
     }
}
二、前端请求代码

后端接口处理接口可以是api或者一般处理程序ashx,这里就不一一贴了。
前端ajax请求代码如下(返回的json结果可以自由处理输出到页面):

$.ajax({
    type: "post",
    url: '后端处理接口地址',
    data: {
        cityCode: cityCode//城市编码
    },
    success: function (result) {
        if (result.status == 200) {//请求成功加载信息
			console.log(result.data.forecast[0].type);
        }
        else {
			console.log(result);
        }
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log("错误:" + XMLHttpRequest);
    }
});
三、城市编码json

weather_city.json文件下载

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/954350.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号