天天看點

java url 20_java URL使用

1 基本使用

package com.lzs.net;

import java.net.MalformedURLException;

import java.net.URL;

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;

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();

}

}