标签:
获取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();
标签:
原文地址:http://www.cnblogs.com/taoshihan/p/5513807.html