zoukankan      html  css  js  c++  java
  • [javaSE] 网络编程(URLConnection)

    获取URL对象,new出来,构造参数:String的路径

    调用URL对象的openConnection()方法,获取URLConnection对象

    调用URLConnection对象的getInputStream()方法,获取输入流InputStream对象

    读取输出流

    import java.io.InputStream;
    import java.net.URL;
    import java.net.URLConnection;
    
    
    public class UrlDemo {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            try {
                URL url=new URL("http://www.baidu.com");
                URLConnection conn=url.openConnection();
                InputStream is=conn.getInputStream();
                byte[] buf=new byte[1024];
                int len=0;
                StringBuilder sb = new StringBuilder();
                while((len=is.read(buf))!=-1){
                    sb.append(new String(buf,0,len));
                }
                System.out.println(sb.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    }

    PHP版:

    调用函数fopen()方法,获取到输入流资源,参数:String路径,String’r’读

    循环读取,条件:feof()读取到末尾不为真

    调用fgets()方法,读取一行获取到String,参数:流资源,长度

    <?php
    class UrlDemo{
        public static function main(){
            $url="http://www.baidu.com";
            $fp=fopen($url,'r');
            $buf=1024;
            $str="";
            while(!feof($fp)){
                $str.=fgets($fp,$buf);
            }
            echo $str;
        }
    }
    
    UrlDemo::main();
  • 相关阅读:
    进程与线程
    闭包
    form表单提交
    让图片在div盒子中水平垂直居中
    第一个shell脚本——修改配置文件
    Linux系统find命令的常用方法
    Linux使echo命令输出结果带颜色
    Linux面试题
    无人值守批量安装
    Linux系统PXE高效批量网络装机的配置
  • 原文地址:https://www.cnblogs.com/taoshihan/p/5513807.html
Copyright © 2011-2022 走看看