Http方式获取网络数据
通过以下代码可以根据网址获取网页的html数据,安卓中获取网络数据的时候会用到,而且会用Java中的sax方式解析获取到数据。(sax解析主要是解析xml)具体代码如下:
package com.wyl; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class HttpDownloadTest { public static void main(String[] args) { StringBuffer sb = new StringBuffer(); try { //创建url对象 URL url = new URL("http://www.baidu.com"); //创建connection URLConnection conn = url.openConnection(); //使用io流读取数据 InputStream ips = conn.getInputStream(); InputStreamReader reader = new InputStreamReader(ips); BufferedReader br = new BufferedReader(reader); // String s = br.readLine(); while(br.readLine()!=null){ //返回读取出来的结果 sb.append(br.readLine()); } System.out.println(sb); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
实例2:
package wyl; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class httpdownloadtest { public static void main(String[] args) { // getSDPath(); // System.out.println("路径:"+getSDPath()); System.out.println("xml:"+getXml("http://www.weibo.com")); System.out.println("======"); System.out.println("xml:"+getXml("http://www.baidu.com")); } /** * 获取sd卡路径 * @return */ // public static String getSDPath(){ // return Environment.getExternalStorageDirectory().getPath(); // } /** * 根据网址获取转换后的xml * @param dizhi * @return */ public static String getXml(String dizhi){ BufferedReader bufferedreader; String xml = ""; StringBuffer sb = new StringBuffer(); try { URL url = new URL(dizhi); //1 获取一个连接 URLConnection conn = url.openConnection(); //2 把inputStream封装成为BufferedReader, bufferedreader = new BufferedReader(new InputStreamReader(conn.getInputStream())); while(bufferedreader.readLine()!=null){ //3 从缓冲流里读出数据 sb.append(bufferedreader.readLine()); } //4 把StringBuffer转换为String xml = sb.toString(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return xml; } }