java获取google 的简单天气预报

注意weather那写入城市的拼音转化一下就行打开之后是XML格式的然后再提取


  
  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("weather.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).getNodue()+","+n2.item(1).getAttributes().item(0).getNodue()+"℃-"+n2.item(2).getAttributes().item(0).getNodue()+"℃";
54         }catch(Exception e)
55         {
56             
57         }
58         
59         return str;
60     }
61     
62         
63     
64 }


转载于:http://blog.sina.com.cn/s/blog_606e44ef0100dkym.html

你可能感兴趣的:(java,.net,xml,Blog,Google)