java.net.URL的使用
java.net.URL的使用
以下的例子可以使用于扒取网站的数据
而在实际开发中,很多应用对java.net.URL和IO流进行封装,用返于取得函数回JSON数据;
public static void main(String args[]) throws Exception{String str = getContentFromURL("http://www.baidu.com");System.out.println(str);}private static String getContentFromURL(String urladdr) throws IOException {InputStream is=null;try {URL url=new URL(urladdr);URLConnection conn=url.openConnection();conn.setRequestProperty ("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");is=conn.getInputStream();BufferedReader br=new BufferedReader(new InputStreamReader(is));StringBuilder sb=new StringBuilder();String str=null;while((str=br.readLine())!=null){sb.append(str+"\n");}conn.getInputStream().close();return sb.toString();}finally{if(is!=null){try {is.close();} catch (IOException e) {}}}}