Use WebService to call Sina's weather forecast function
Use WebService to query weather forecasts
This is the weather web service.Code, Transferred from the book.
1. Add a "Web Service" under the root directory of the website and name it "Weather". Be sure not to build the ASPX page.
Using system;
Using system. Web;
Using system. collections;
Using system. Web. Services;
Using system. Web. Services. Protocols;
Using system. net;
Using system. IO;
/// <Summary>
/// Summary of weather
/// </Summary>
[WebService (namespace = "http://tempuri.org/")]
[Webservicebinding (conformsto = wsiprofiles. basicprofile1_1)]
Public class weather: system. Web. Services. WebService {
Public Weather (){
// If you use the designed component, uncomment the following line
// Initializecomponent ();
}
[Webmethod]
Public String getweather (string City)
{
String weacherhtml = string. empty;
// Convert the encoding type of input parameters
String mycity = system. Web. httputility. urlencode (city, system. Text. unicodeencoding. getencoding ("gb2312 "));
// Initialize a new webrequest
Httpwebrequest webrt = (httpwebrequest) webrequest. Create ("http://php.weather.sina.com.cn/search.php? City = "+ mycity );
Httpwebresponse webrs = (httpwebresponse) webrt. getresponse ();
// Return data streams from Internet Resources
Stream stream = webrs. getresponsestream ();
// Read data streams
Streamreader SRM = new streamreader (stream, system. Text. encoding. Default );
// Read data
Weacherhtml = SRM. readtoend ();
SRM. Close ();
Stream. Close ();
Webrs. Close ();
// View the HTML source file for different websites
Int start = weacherhtml. indexof ("weather condition begin"); // The character location
Int end = weacherhtml. indexof ("weather condition end ");
Return weacherhtml. substring (start + 14, end-Start );
}
}
2. When you add a web reference and select "Web service in this solution", the "Weather" service is automatically found.
3. Create An ASPX page and put the three controls button1, label1, and textbox1 on the page. The Code is as follows:
Protected void button#click (Object sender, eventargs E)
{
Weather myweather = new weather ();
Label1.text = myweather. getweather (textbox1.text );
}
Run the test at this time and you will see that the weather forecast of Sina is called.