JSP obtains weather forecast data from WebService.
There are related code on the Internet, but it is complicated. I have improved it. It is easy to implement.
Package com. XXX. Web;
Import java. Io .*;
Import java.net .*;
Import javax. xml. parsers. documentbuilder;
Import javax. xml. parsers. documentbuilderfactory;
Import org. W3C. Dom. Document;
Import org. W3C. Dom. node;
Import org. W3C. Dom. nodelist;
Public class weather {
Private Static string _ url = "http://www.wopos.com/webservice/Weather.asmx/getWeather? Mcity = ";
Private weather (){
}
/**
* @ Param cityname
* @ Return
*/
Private Static inputstream getsoapinputstream (string cityname ){
Try {
/*
* URL url = new URL (_ URL + cityname); httpurlconnection Hc =
* (Httpurlconnection) URL. openconnection (); HC. Connect ();
* Inputstream urlstream = HC. getinputstream (); Return urlstream;
*/
Return new URL (_ URL + cityname). openstream ();
} Catch (exception ex ){
Return NULL;
}
}
/**
* Use W3C Dom to explain the returned XML.
* @ Param cityname
* @ Return
*/
Public static string getweatherbycityname (string cityname ){
Try {
Document Doc;
Documentbuilderfactory DBF = documentbuilderfactory. newinstance ();
DBF. setnamespaceaware (true );
Documentbuilder DB = DBF. newdocumentbuilder ();
Inputstream is = getsoapinputstream (cityname );
If (is = NULL ){
Return NULL;
}
Doc = dB. parse (is );
Nodelist NL = Doc. getelementsbytagname ("string ");
Node n = NL. Item (0 );
String weather = n. getfirstchild (). getnodevalue ();
Is. Close ();
Return weather;
} Catch (exception e ){
E. printstacktrace ();
Return NULL;
}
}
/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
System. Out. Print (getweatherbycityname ("Beijing "));
}
}
Get a String object, and the rest will be well processed.
Final effect: