JSP extracts weather forecast data from WebService, which is a simplified code [effect chart].

Source: Internet
Author: User

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:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.