java calls weather forecast webservice

Code download: https://download.csdn.net/download/sinat_36710456/10369688


1. Description


Reprint the webService address of the weather forecast used in this blog:

http://www.webxml.com.cn/WebServices/WeatherWebService.asmx

Now changed to: http://www.webxml.com.cn/WebServices/WeatherWS.asmx?wsdl



2. Examples and descriptions of relevant information invocation


1. Create a new java class: WeatherUtil.java

package com.test.util;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
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 WeatherUtil {
/**
Parse the XML file stream returned by the server

* @param city the city name entered by the user
* @return string is split with #
*/
public  String getWeather(String city) {
try {
//Use Dom parsing
Document doc;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
//Get the stream returned after calling the interface
InputStream is = getSoapInputStream(city);
doc = db.parse(is);
//The element tag of xml is "<string>value 1</string><string>value 2</string>..."
NodeList nl = doc.getElementsByTagName("string");
StringBuffer sb = new StringBuffer();
for (int count = 0; count < nl.getLength(); count++) {
Node n = nl.item(count);
if(n.getFirstChild().getNodeValue().equals("The query result is empty!")) {
sb = new StringBuffer("#") ;
break ;
}
//Parse and use "#" as the delimiter, splicing and returning the result
sb.append(n.getFirstChild().getNodeValue() + "#");
}
is.close();
return sb.toString();
} catch (Exception e) {
e.printStackTrace ();
return null;
}
}
/*
The user sends the SOAP request to the server and returns the input stream returned by the server

* @param city the city name entered by the user
* @return the input stream returned by the server for the client to read
* @throws Exception
* @Note: There are four request header formats: 1. SOAP 1.1; 2. SOAP 1.2; 3. HTTP GET; 4. HTTP POST
参考---》http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?op=getWeatherbyCityName
*/
private  InputStream getSoapInputStream(String city) throws Exception {
try {
// get request specification
String soap = getSoapRequest(city);
if (soap == null) {
return null;
}
//Called weather forecast webserviceURL
URL url = new URL("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx");
URLConnection conn = url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Length", Integer.toString(soap.length()));
conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
//The interface method called is " getWeatherbyCityName "
conn.setRequestProperty("SOAPAction", "http://WebXml.com.cn/getWeatherbyCityName");
OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");
osw.write(soap);
osw.flush();
osw.close ();
//Get the stream returned by webserivce
InputStream is = conn.getInputStream();
return is;
} catch (Exception e) {
e.printStackTrace ();
return null;
}
}
/*
Get the SOAP request header and replace the glyph with the city entered by the user

* @param city: the city name entered by the user
* @return the SOAP request specification that the client will send to the server
* @Note: There are four request header formats: 1. SOAP 1.1; 2. SOAP 1.2; 3. HTTP GET; 4. HTTP POST
参考---》http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?op=getWeatherbyCityName
* This article uses: SOAP 1.1 format

*/
private  String getSoapRequest(String city) {
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
+ "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
+ "<soap:Body><getWeatherbyCityName xmlns=\"http://WebXml.com.cn/\">"
+ "<theCityName>" 
+ city
+ "</theCityName></getWeatherbyCityName>"
+ "</soap:Body></soap:Envelope>");
return sb.toString();
}
}

Note: The xml file returned by webservice is as follows


2. Create a new test class: TestWeather.java

package com.util;
import com.test.util.WeatherUtil;
public class TestWeather {
/**
test
*/
public static void main(String[] args) throws Exception {
WeatherUtil weath=new WeatherUtil();

//查看城市:济南
String weather=weath.getWeather("济南");
String len[]=weather.split("#");
for(int i=0;i<len.length-1;i++){
System.out.println(len[i]);
}
/**
* 打印结果:
* 山东
* 济南
* 54823
* 54823.jpg
  * 2016-3-5 13:52:01
* 4℃/14℃
* 3月5日 多云转晴
* 北风3-4级转南风微风
* 1.gif
* 0.gif
* 今日天气实况:气温:12℃;风向/风力:东北风 2级;湿度:23%;紫外线强度:弱。空气质量:良。
* 紫外线指数:弱,辐射较弱,涂擦SPF12-15、PA+护肤品。
      感冒指数:极易发,强降温,湿度较大,极易感冒。
      穿衣指数:较冷,建议着厚外套加毛衣等服装。
      洗车指数:较适宜,无雨且风力较小,易保持清洁度。
      交通指数:良好,气象条件良好,车辆可以正常行驶。
空气污染指数:良,气象条件有利于空气污染物扩散。
  * 7℃/17℃
* 3月6日 多云
* 南风微风
* 1.gif
* 1.gif
* 4℃/16℃
* 3月7日 多云
* 南风微风转北风3-4级
* 1.gif
* 1.gif
*/}
}

三、以上代码已经测试通过,可以直接根据需要改动并使用



转载:https://blog.csdn.net/high2011/article/details/49445269

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324741053&siteId=291194637