使用POST请求获取一个简单的天气预报
使用到的技术
数据库 数据库操作 XML转json json或者XML写入数据库 HTTP的GET请求
请求代码
public static string Get(string url)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
try
{
using (StreamReader reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
}
}
finally
{
stream.Close();
}
return result;
}
发送请求示例
public static string GetWeathrtInfo(string cityName)
{
int cityCode = GetCityCodeByCityName(cityName);
string result = "";
if (cityCode == 000000)
{
result = "未能获取到城市信息(城市天气预报代码)";
return result;
}
else
{
string url = "http://www.weather.com.cn/data/sk/" + cityCode + ".html";
result = HttpRequestHelper.Get(url);
}
return result;
}
private static int GetCityCodeByCityName(string cityName)
{
int code = 0;
string c = CityInfoJson.Info.Replace("-", "");
List<County> cv = JsonConvert.DeserializeObject<List<County>>(c);
County county = cv.Find(x => x.name == cityName);
if (county == null)
{
code = 000000;
}
else
{
code = int.Parse(county.weatherCode);
}
ShuJuKuChaXun("北京");
return code;
}
其中CityInfoJson.Info的信息在这篇博客
https://blog.csdn.net/GoodCooking/article/details/124083226
切勿直接将信息复制到IDE中,会把IDE直接卡死。 复制到txt中,然后去读取
信息处理
读取XML信息,然后
string[] str1 = File.ReadAllLines(@"C:\Users\GoodCooking\Desktop\wyh_Post\wyh_Post\hello.txt");
for (int i = 0; i < str1.Length; i++)
{
if (str1[i].Contains("</city>"))
{
str1[i] = "";
}
if (str1[i].Contains("</province>"))
{
str1[i] = "";
}
if (str1[i].Contains("<city id="))
{
str1[i] = "";
}
if (str1[i].Contains("<province id="))
{
str1[i] = "";
}
}
File.WriteAllLines(@"C:\Users\GoodCooking\Desktop\wyh_Post\wyh_Post\hello_new.xml", str1);
然后将新的文件拷贝到浏览器的XML转JSON中去,将XML转成JSON,并创建对象,将转好的JSON,保存在记事本中,在CityInfoJson中读取读取保存的json,赋值给info。
namespace wyh_Post
{
public class County
{
public string id { get; set; }
public string name { get; set; }
public string weatherCode { get; set; }
}
public class China
{
public List<County> county { get; set; }
}
public class Root
{
public China China { get; set; }
}
}
|