[Java] 讀取URL 內HTML

有時須要在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>>");

 

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.