java SE基础(URL访问网络资源)

/*        1。URL的构造方法*/

            public URL(String spec){}        //根据 String 表示形式创建 URL 对象
            public URL(String protocol, String host, String file){}        //根据指定的 protocol 名称、host 名称和 file 名称创建 URL

/*        2。URL的操作*/

            public InputStream openStream(){}        //打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream
            public URLConnection openConnection(){}        //返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接
            

/*        3。URLConnection的构造方法*/

            protected  URLConnection(URL url){}        //构造一个到指定 URL 的 URL 连接
        

/*        4。URLConnection的字段*/

            protected boolean doInput    //此变量由 setDoInput 方法设置,默认值为 true;将doInput标志设置为 true,指示应用程序要从 URL 连接读取数据
            protected boolean doOutput    //此变量由 setDoOutput方法设置,默认值为false;将doOutput标志设置为true,指示应用程序要向 URL 连接写入数据

/*        5。URLConnection的操作*/

            public InputStream getInputStream(){}    //返回从此打开的连接读取的输入流
            public OutputStream getOutputStream(){}    //返回写入到此连接的输出流
            

/*        6。例如:*/

public class URLReader {
	public static void main(String[] args) throws IOException {
		URL web  = new URL("https://www.baidu.com/");
		BufferedReader br = new BufferedReader(new InputStreamReader(web.openStream()));
		
		String line = null;
		while( (line = br.readLine()) != null ){
			System.out.println(line);
		}
		br.close();
		
		System.out.println("--------------------");
		
		URLConnection webc = web.openConnection();
		br = new BufferedReader(new InputStreamReader(webc.getInputStream()));
		while( (line = br.readLine()) != null ){
			System.out.println(line);
		}
		br.close();
	}
}

public class URLWrite {
	public static void main(String[] args) throws IOException {
		String stringToReverse = "-----------------------------------------------------------------------------------------";
		URL url = new URL("http://www.baidu.com");			//利用URL对象创建URLConnection对象
		URLConnection urlc = url.openConnection();
		
		urlc.setDoOutput(true);						//doOutput设置为true,表示应用程序要将数据写入URL链接
		
		PrintWriter pw = new PrintWriter(urlc.getOutputStream());       //获取打印输出流
		pw.print("string="+stringToReverse);
		pw.close();
		
		BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
		String line = null;
		while( (line = br.readLine() ) != null){
			System.out.println(line);
		}
		br.close();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值