有時須要在Project中讀取URL內容, 其實並不需要其他Library 支援, 只須內建的功能亦已經足夠基本使用.UrlReader.java
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import org.apache.commons.lang3.StringUtils; public class UrlReader { // Get URL content in HTML format. public String read(String url) throws Exception { String result=StringUtils.EMPTY; // Open and read URL. URL targetUrl = new URL(url); BufferedReader in = new BufferedReader(new InputStreamReader(targetUrl.openStream())); // Append lines to result. String inputLine=StringUtils.EMPTY; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); result+=inputLine+System.lineSeparator(); } in.close(); return result; } }
存取方法:
urlReader.read("<<Target URL>>");
Leave a Reply