1 基本使用
package com.lzs.net;import java.net.MalformedURLException;import java.net.URL;/** * Created by zaish on 2016-3-20. */public class URLDemo1 { public static void main(String[] args) throws MalformedURLException { URL url= new URL("http://www.baidu.com:80/index.html#aa?username=lzs");//绝对路径构建 System.out.println(url.getProtocol()); System.out.println(url.getHost()); System.out.println(url.getPort()); System.out.println(url.getFile()); System.out.println(url.getPath()); System.out.println(url.getRef());//锚点 System.out.println(url.getAuthority());// System.out.println(url.getQuery());//?参数,如果存在锚点返回null System.out.println(url.getUserInfo()); URL url1= new URL("http://www.baidu.com:80/a/");//相对路径构建 URL url2=new URL(url1,"b.txt"); System.out.println(url2.toString()); }}
2 获取某网页源码源码
package com.lzs.net;import java.io.*;import java.net.URL;/** * Created by zaish on 2016-3-20. */public class URLDemo2 { public static void main(String[] args) throws IOException { URL url= new URL("http://www.baidu.com"); InputStream is=url.openStream();// int len=0;// byte[] flust=new byte[1024];// while (-1!=(len=is.read(flust))){// System.out.println(new String(flust,0,len));// }// is.close(); String msg=null; BufferedReader br=new BufferedReader(new InputStreamReader(is,"utf-8")); BufferedWriter bw=new BufferedWriter(new FileWriter("baidu.html")); while (null!=(msg=br.readLine())){ bw.append(msg); bw.newLine(); } bw.flush(); bw.close(); br.close(); }}