/** * 使用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 Host: " + strHost + " Connection: Close "; 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 + " "); } //要关闭各种 bufferedReader.close(); inputStreamReader.close(); inputStream.close(); outputStream.close(); socket.close(); } catch (Exception ex) { } }