获取天气预报

using System;
using System.Collections.Generic;
using System.Web;
using System.Net;
using System.IO;

public class WeatherHelper
{
    public WeatherHelper()
    { }

    /// <summary>
    /// 获取今天气温,远程捕获
    /// </summary>
    public static string GetWeatherToday(string CityCode)
    {
        string strUrl = "http://weather.china.com.cn/city/"+CityCode+"_pic2.html".Trim();
        string WeatherToday = "";
        if (UrlExistsUsingSockets(strUrl))
        {
            WebRequest wreq = WebRequest.Create(strUrl);
            WebResponse wresp = (WebResponse)wreq.GetResponse();
            Stream s = wresp.GetResponseStream();
            StreamReader sr = new StreamReader(s, System.Text.Encoding.GetEncoding("utf-8"));
            string HTML = sr.ReadToEnd();
            int laststr = HTML.LastIndexOf("℃");
            if (laststr > 0)
            {
                string Newhtml = HTML.Substring(0, laststr + 1);
                int startstr = Newhtml.LastIndexOf(">");
                int mylen = laststr - startstr;
                WeatherToday = Newhtml.Substring(startstr + 1, mylen);
            }
            else
            {
                WeatherToday = "天气预报解析不成功!";
            }
        }
        else
        {
            WeatherToday = "获取天气预报失败!";
        }
        return WeatherToday;
    }

    /// <summary>
    /// 方法一、检测远程url是否存在
    /// </summary>
    private static bool UrlExistsUsingHttpWebRequest(string url)
    {
        try
        {
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
            myRequest.Method = "HEAD";
            myRequest.Timeout = 100;
            HttpWebResponse res = (HttpWebResponse)myRequest.GetResponse();
            return (res.StatusCode == HttpStatusCode.OK);
        }
        catch (System.Net.WebException we)
        {
            System.Diagnostics.Trace.Write(we.Message);
            return false;
        }
    }

    /// <summary>
    /// 方法二、检测远程url是否存在
    /// </summary>
    private static bool UrlExistsUsingSockets(string url)
    {
        if (url.StartsWith("http://")) url = url.Remove(0, "http://".Length);
        try
        {
            IPHostEntry ipHost = Dns.GetHostEntry(url); //GetHostEntry
            return true;
        }
        catch (Sockets.SocketException se)
        {
            System.Diagnostics.Trace.Write(se.Message);
            return false;
        }
    }
}

原文地址:https://www.cnblogs.com/Elgin/p/2238194.html