Java讀取URL中的資源
阿新 • • 發佈:2019-01-06
URL物件呼叫InputStream openStream() 方法可以返回一個輸入流,該輸入流指向URL物件包含的資源。通過該輸入流可以將伺服器上的資訊列印到客戶端。
Main.java
package URL;
import java.util.Scanner;
import java.net.*;
public class Main {
public static void main(String []args){
Scanner in = new Scanner(System.in);
URL url;
Thread readURL;
Look look = new Look();
System.out.println("輸入URL資源");
String source = in.nextLine();
try {
url = new URL(source);
look.setURL(url);
readURL = new Thread(look);
} catch (MalformedURLException e) {
e.printStackTrace();
}
readURL = new Thread(look);
readURL.start();
}
}
Look.java
package URL;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
public class Look implements Runnable{
URL url;
public void setURL(URL url){
this.url = url;
}
public void run(){
try {
InputStream in = url.openStream();
byte [] b = new byte[1024];
int n = -1;
while((n = in.read(b)) != -1){
String str = new String(b,0,n);
System.out.println(str);
}
} catch (IOException e) {
System.out.println(e);
}
}
}
例如抓取百度的資源: