java使用socket读取网页
/** * 使用socket读取网页内容 */ private static void socketReadWebPage() { try { String strHost = "www.baidu.com"; InetSocketAddress socketAddress = new InetSocketAddress(strHost, 80); Socket socket = new Socket(); socket.connect(socketAddress); String strSend = "GET / HTTP/1.1\r\nHost: " + strHost + "\r\nConnection: Close\r\n\r\n"; OutputStream outputStream = socket.getOutputStream(); InputStream inputStream = socket.getInputStream(); byte[] bytes = strSend.getBytes(); outputStream.write(bytes); outputStream.flush(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line; while((line = bufferedReader.readLine()) != null) {
System.out.println(line + "\r\n"); } //要关闭各种 bufferedReader.close(); inputStreamReader.close(); inputStream.close(); outputStream.close(); socket.close(); } catch (Exception ex) { } }