Java使用URLConnection类进行爬虫操作,URLConnection是一个抽象类,表示指向URL指定资源的活动连接。
使用URLConnection类的程序遵循以下基本步骤:
构造一个URL对象;
调用这个URL对象的openConnection()获取一个对应该URL的URLConnection对象;
配置这个URLConnection;
读取首部字段;
获得输入流并读取数据;
获得输出流并写入数据;
关闭连接;
public static void main(String[] args) {
try {
//URL设置为要访问的网址
URL url = new URL("http://www.baidu.com/");
URLConnection urlConnection = url.openConnection();
int i=0;
String header=urlConnection.getHeaderField(i);
while (header!=null){
System.out.println(header);
header=urlConnection.getHeaderField(++i);
}
InputStream is = urlConnection.getInputStream();
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) != -1) {
System.out.println(new String(buf, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
}
}
URLConnection默认使用GET请求方法,想要使用其他方法建议使用HttpURLConnection类
java.net.HttpURLConnection类是URLConnection的抽象子类。它提供了另外一些方法,在处理http URL时尤其有帮助
public static void main(String[] args) {
try{
URL url=new URL("http://www.baidu.com");
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
int i=0;
String header=httpURLConnection.getHeaderField(i);
while (header!=null){
System.out.println(header);
header=httpURLConnection.getHeaderField(++i);
}
System.out.println();
InputStream is=httpURLConnection.getInputStream();
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) != -1) {
System.out.println(new String(buf, 0, len));
}
}catch (IOException e){
e.printStackTrace();
}
}
更多请见 https://blog.csdn.net/z1790424577/article/details/82938624
本文章使用limfx的vscode插件快速发布