今天用Java实现了一个类URLAnalysis,其中的getContent方法可用于实现获取特定网页源代码,main函数用于测试。
代码如下:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class URLAnalysis {
public static String getContent(String urlString) throws Exception {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
String ans = "";
while ((line = reader.readLine()) != null){
ans += line + "\n";
}
return ans;
}
public static void main(String[] args) throws Exception {
String ans = getContent("http://www.baidu.com");
System.out.println(ans);
}
}
posted on 2015-02-11 21:47
marchalex 阅读(311)
评论(0) 编辑 收藏 所属分类:
java小程序