悉野小楼

导航

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) { } }

 

posted on 2020-06-02 10:19  悉野  阅读(652)  评论(0编辑  收藏  举报