你可以使用 java.net.URL
或者 java.net.URLConnection
.
如下访问百度首页并将文件保存到D:/Baidu.html
public class TestJavaURL {
public static void curl(String addr){
try {
URL url = new URL(addr);
String line = "";
FileOutputStream fo = new FileOutputStream(new File("D:/Baidu.html"));
BufferedOutputStream oBuffer = new BufferedOutputStream(fo);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8"));
while ((line = reader.readLine()) != null){
System.out.println(line);
line += "\n";
oBuffer.write(line.getBytes());
}
oBuffer.flush();
oBuffer.close();
}catch (MalformedURLException e){
System.out.println(e.getMessage());
}catch (IOException e){
System.out.println(e.getMessage());
}
}
}
注意直接写
www.baidu.com
会报错:no protocol
: www.baidu.com
。你需要加上 http:// 前缀来指明协议
运行:
public class MainClass {
public static void main(String[] args) {
TestJavaURL.curl("http://www.baidu.com");
}
}