Java simple web page capture and java crawling
Background
1. Introduction to tcp
1. tcp implements point-to-point transmission in the Network
2 transmission is through ports and sockets
Ports provide different types of transmission (for example, http port is 80)
1) sockets can be bound to a specific port and provide the transmission function
2) one port can connect multiple sockets
Introduction to binary URL
A URL is a simple representation of the location and access method of resources that can be obtained from the Internet. It is the address of a standard resource on the Internet.
Each file on the Internet has a unique URL. It contains information that specifies the location of the file and how the browser should handle it.
To sum up, we need to capture the content of the web page, in essence, through the url to capture the content of the Web page.
Java provides two methods:
One is to read the webpage directly from the URL
One is to read the webpage through URLConnection.
URLConnection is a class centered on http and provides many functions for connecting to http.
This article provides the URLConnection-based instance code.
Before that, let's take a look at the url exceptions. For more information about the java exception mechanism, see the previous blog.
URL construction exception MalformedURLException generation condition: the url string is empty or unidentifiable.
Exception IOException condition for establishing URLConnection: openConnection fails. Note that the Code has not been connected to the remote connection before openConnection, but is only used to prepare for remote connection.
To sum up the final code
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;public class SimpleNetSpider { public static void main(String[] args) { try{ URL u = new URL("http://docs.oracle.com/javase/tutorial/networking/urls/"); URLConnection connection = u.openConnection(); HttpURLConnection htCon = (HttpURLConnection) connection; int code = htCon.getResponseCode(); if (code == HttpURLConnection.HTTP_OK) { System.out.println("find the website"); BufferedReader in=new BufferedReader(new InputStreamReader(htCon.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } else { System.out.println("Can not access the website"); } } catch(MalformedURLException e ) { System.out.println("Wrong URL"); } catch(IOException e) { System.out.println("Can not connect"); } }}
References:
Http://docs.oracle.com/javase/tutorial/networking/urls/index.html