Java URL与URLConnection

大家都知道URL就是统一资源定位器

   它由协议名和资源名组成

   也不多说什么了,就拿URLConnection类举个例子吧,做一个获取网站源码的代码

 

public class URLDemo {
 public static void main(String[] args) {
  Scanner scan = new Scanner(System.in);
  
        System.out.println("请输入网址:");
  String urlStr ="http://"+scan.next ();
  try {
   URL url = new URL(urlStr);        // 将urlstr字符串网址实例化为URL定位地址s

   URLConnection urlConn = url.openConnection();   //打开网站链接s
   BufferedReader reader = new BufferedReader(new InputStreamReader(
     urlConn.getInputStream()));            //实例化输入流,并获取网页代码
   String s;                                         //依次循环,至到读的值为空
   StringBuilder sb = new StringBuilder();
   while ((s = reader.readLine()) != null) {
    sb.append(s);    
   }
   reader.close();
   BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\1.html"));     //write写入文件(字节流)
   bw.write(sb.toString());
   bw.flush();
   bw.close();
   System.out.println("另存为成功!");
  }

  catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

}

就是以上代码

你可能感兴趣的:(url,urlconnection)