2009年6月17日 星期三

簡單獲取google天氣報告

簡單獲取google天氣報告

http://www.google.com/ig/api?hl=zh_tw&weather=hk



























































1 package com.pmjava.util;
2
3 import java.io.BufferedReader;
4 import java.io.BufferedWriter;
5 import java.io.FileWriter;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.InputStreamReader;
9 import java.net.MalformedURLException;
10 import java.net.URL;
11
12
13 import java.io.*;
14 import org.w3c.dom.*;
15 import javax.xml.parsers.*;
16
17 public class GetWeather {
18
19
20 public String getweather(String city)
21 {
22 try {
23 URL ur = new URL("http://www.google.com/ig/api?hl=zh_cn&weather="+city);
24 InputStream instr = ur.openStream();
25 String s, str;
26 BufferedReader in = new BufferedReader(new InputStreamReader(instr));
27 StringBuffer sb = new StringBuffer();
28
29 Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("weather.txt"), "utf-8"));
30 while ((s = in.readLine()) != null) {
31 sb.append(s);
32 }
33 str = new String(sb);
34 out.write(str);
35 out.close();
36 in.close();
37
38
39 } catch (MalformedURLException e) {
40 e.printStackTrace();
41 } catch (IOException e) {
42 e.printStackTrace();
43 }
44 File f=new File("cityweather.txt");
45 DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
46 String str=null;
47 try{
48 DocumentBuilder builder=factory.newDocumentBuilder();
49 Document doc = builder.parse(f);
50 NodeList nl = (NodeList) doc.getElementsByTagName("forecast_conditions");
51 NodeList n2=nl.item(0).getChildNodes();
52
53 str=n2.item(4).getAttributes().item(0).getNodeValue()+","+n2.item(1).getAttributes().item(0).getNodeValue()+"℃-"+n2.item(2).getAttributes().item(0).getNodeValue()+"";
54 }catch(Exception e)
55 {
56
57 }
58
59 return str;
60 }
61
62
63
64 }

沒有留言: