Example of Java scraping web data

  • 2020-04-01 03:01:06
  • OfStack

Here are some examples:

Grab baidu home page content:


URL url = new URL("http://www.baidu.com");
HttpURLConnection urlCon=(HttpURLConnection)url.openConnection();
urlCon.setConnectTimeout(50000);
urlCon.setReadTimeout(300000);
DataInputStream fIn;
byte[] content = new byte[MAX_FILE_SIZE];
fIn = new DataInputStream(urlCon.getInputStream());
int size = 0,f_size = 0;
while((size = fIn.read(content,f_size,2048))> 0){
    f_size += size;
}

In the code we will baidu home page content stored in a byte array, of course we have IO stream can also be stored in the file.


Related articles: