zoukankan      html  css  js  c++  java
  • WebServic调用天气预报服务

         在项目开发中,我们除了发布WebService提供客户调用外,也经常需要调用一些客户或者第三方的WebService服务,这里就通过一个Demo来演示调用一个第三方的天气预报服务。

    1.天气预报服务接口说明

    这里以http://www.webxml.com.cn/WebServices/WeatherWebService.asmx这个天气预报服务为例

    2.新建空mvc项目MvcAppService

    3.引入Web服务。在项目引用上右键,选择“添加服务引用”,如下图:

    4.在弹出的添加服务引用窗口单击“高级”按钮,如下图:

    5.在弹出的窗体中单击“添加Web引用”按钮,如下图:

    6.输入Web服务地址,修改Web引用名称,如下图:

     7.从 http://www.webxml.com.cn/images/weather.zip下载天气图片,然后解压文件,将文件夹weather复制到项目Content文件夹下(空项目没有Content文件夹,自己创建)

    8.添加Home控制器,和两个GetWeather方法,实现代码。

     public ActionResult GetWeather()
            {
                return View();
            }
    
            [HttpPost]
            public ActionResult GetWeather(string city)
            {
                Weather.WeatherWebService client = new Weather.WeatherWebService();
                var strlist = client.getWeatherbyCityName(city);
                if(strlist[8] == "")
                {
                    ViewBag.Msg = "暂时不支持你查询的城市";
                }
                else
                {
                    ViewBag.ImgUrl = @"/Content/weather/" + strlist[8];
                    ViewBag.General = strlist[1] + " " + strlist[6];
                    ViewBag.Actually = strlist[10];
                }
                return View();
            }

    9.添加GetWeather视图,代码如下:

    @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>GetWeather</title>
    </head>
    <body>
        @using (Html.BeginForm("GetWeather", "Home", FormMethod.Post))
        {
            <div>请输入查询的城市:@Html.TextBox("city")<input type="submit" value="查询" /></div>
            <div>
                天气概况:@ViewBag.General
                @if (!string.IsNullOrEmpty(ViewBag.ImgUrl as string))
                {
                    <img src="@ViewBag.ImgUrl" />
                }
                <div>天气实况:@ViewBag.Actually</div>
                <div>@ViewBag.Msg</div>
            </div>
        }
    </body>
    </html>

    10.运行结果如下:

  • 相关阅读:
    Reverse Nodes in k-Group [LeetCode]
    Text Justification [LeetCode]
    Path Sum [LeetCode]
    Multiply Strings [LeetCode]
    Populating Next Right Pointers in Each Node II [Leetcode]
    013 集合
    012 元组
    02 isdecimal(), isdigit(), isnumeric()
    011 字符串的内置方法 三
    010 字符串的内置方法 二
  • 原文地址:https://www.cnblogs.com/marshhu/p/6820189.html
Copyright © 2011-2022 走看看