在程序中,往往我们会调用远端接口,获取返回的数据,通常调用webservice接口,获取结果数据,下面就直接给予代码,敬请参考!
package com.wgy.control; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import com.wgy.util.DateUtils; public class Weather { private static String WEATHER_SERVICES_URL = "http://www.gpsso.com/webservice/weather/weatherinfo.asmx/"; /** * 城市代码 /陕西西安: 101110101 */ private static int CITICODE = 101110101; private static String WEATHER_QUERY_URL = WEATHER_SERVICES_URL + "GetToDayWeatherInfo?CityCode=" + CITICODE; public static void main(String[] args) throws Exception { String desc = "今天是" + DateUtils.getYear() + "," + DateUtils.getWeekOfDate(new Date()); desc += new Weather().getSoapInputStream(WEATHER_QUERY_URL); System.out.println(desc); new Weather().getSoapAsList(WEATHER_QUERY_URL); } /** * 返回远程接口String字符串 * @param url * @return */ public String getSoapInputStream(String url) { BufferedReader br = null; URLConnection urlConn = null; String str = "", info = ""; try { URL urlObj = new URL(url); urlConn = urlObj.openConnection(); urlConn.connect(); InputStreamReader isr = new InputStreamReader( urlConn.getInputStream()); br = new BufferedReader(isr); while ((str = br.readLine()) != null) { info += str + "\n"; } System.out.println(info); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return str; } public List<String> getSoapAsList(String url){ List<String> list = new ArrayList<String>(); try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(url); NodeList nl = doc.getElementsByTagName("API"); for (int i = 0; i < nl.getLength(); i++) { System.out.print("list:"+doc.getElementsByTagName("MESSAGE").item(i).getFirstChild().getNodeValue()); } } catch (Exception e) { e.printStackTrace(); } return list; } }