使用URLConnection获取页面返回的xml数据
public static void main(String[] args) throws Exception { String path="http://flash.weather.com.cn/wmaps/xml/hubei.xml"; URL url = new URL(path);//获得url对象 HttpURLConnection conn = (HttpURLConnection)url.openConnection(); //创建URLConnection连接 conn.setReadTimeout(5*1000); conn.setRequestMethod("GET"); BufferedReader bufr=new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));//设置文件输入流的编码,和url的编码一致 String lines=""; String result=""; while ((lines=bufr.readLine())!=null) { result+=lines; } System.out.println(result); }
特殊的当请求页面被gzip压缩过之后
public static void main(String[] args) throws Exception { String path="http://wthrcdn.etouch.cn/WeatherApi?citykey=101010100"; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setReadTimeout(5*1000); conn.setRequestMethod("GET"); BufferedReader bufr=new BufferedReader(new InputStreamReader(new GZIPInputStream(conn.getInputStream()),"UTF-8"));//使用GZIPInputStream解压缩 String lines=""; String result=""; while ((lines=bufr.readLine())!=null) { result+=lines; } System.out.println(result); }