webservice簡單應用(天氣預報)

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Net;
using System.IO;

public class WebServiceWeather : System.Web.Services.WebService {

    public WebServiceWeather () {

        //如果使用設計的組件,請取消註釋以下行
        //InitializeComponent();
    }
    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }
    [WebMethod]
    public string Getweather(string city)
    {
        string weatherhtml = String.Empty;
        //轉換輸入參數的編碼類型
        string mycity = System.Web.HttpUtility.UrlEncode(city, System.Text.UnicodeEncoding.GetEncoding("GB2312"));
        //初始化新的WebRequest
        HttpWebRequest webrt = (HttpWebRequest)WebRequest.Create("http://php.weather.sina.com.cn/search.php?city="+mycity);
        //返回對Internet請求響應
        HttpWebResponse webrs = (HttpWebResponse)webrt.GetResponse();
        //返回Internet資源返回數據流
        Stream stream = webrs.GetResponseStream();

        //讀取數據流
        StreamReader srm = new StreamReader(stream, System.Text.Encoding.Default);
        //從頭到尾,把數據讀到weatherhtml中
        weatherhtml = srm.ReadToEnd();
        //關閉打開的資源
        srm.Close();
        stream.Close();
        webrs.Close();
        //針對不同的網站,以下開始部分和結束部分不同
        //可以通過查看網站的源文件解決
        int start = weatherhtml.IndexOf("天氣狀況 begin");
        int end = weatherhtml.IndexOf("天氣狀況 end");
        //返回一個html的table,預報城市天氣
        return weatherhtml.Substring(start + 14,end-start);
    }
}

 

發佈了47 篇原創文章 · 獲贊 0 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章