java 网络编程 URL类 笔记

来源:互联网 发布:mac pro快捷键 编辑:程序博客网 时间:2024/05/01 20:19
import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.net.URL;import java.net.URLConnection;import org.junit.Test;/** * URL 统一资源定位符 : *  * 一个 URL对象 对应着 互联网上的一个资源  *  * 可以通过URL对象 调用其相应的方法  将资源下载。 * url.getProtocol();//获取url的协议url.getHost();//获取主机url.getPort();//获取端口号url.getPath();//URL对象的 文件路径url.getFile();//URL对象的 文件名url.getRef();//URL在文件中的相对位置url.getQuery();//获取查询条件 * @author Administrator * */public class TestURL {@Testpublic void testurl() throws Exception{//1、创建一个URL对象   类似于File对象 URL  url = new URL("http://127.0.0.1:9080/member/admin!login.action?ouid=123");//获取  URL对象的协议 System.out.println(url.getProtocol());//获取主机名System.out.println(url.getHost());//获取端口号System.out.println(url.getPort());//获取url的文件路径System.out.println(url.getPath());//获取URL对象的 文件名System.out.println(url.getFile());//获取URL在文件中的相对位置System.out.println(url.getRef());//获取查询名 System.out.println(url.getQuery());}//下载  或者读取远程的 文件   音频  文字 文件 @Testpublic void getURLContent() throws Exception{//1.创建一个URL对象 URL  url = new URL("https://www.baidu.com/");InputStream os = url.openStream();byte[] b = new byte[1024];int len;while((len=os.read(b))!=-1){String st = new String(b,0,len);System.out.println(st);}os.close();}//与URL对象 建立连接   即能往服务器写(传入服务器中 )  ,,也能从服务器读取文件 (音频。视频  html等   下载下来 )@Testpublic  void  testInOut() throws Exception{//1.创建一个URL对象 URL  url = new URL("https://www.baidu.com/");URLConnection urlcon =  url.openConnection();FileOutputStream fos = new FileOutputStream(new File("baidu.txt"));InputStream is = urlcon.getInputStream();byte[] b= new byte[1024];int len;while((len=is.read(b))!=-1){fos.write(b, 0, len);fos.flush();}fos.close();is.close();}}

0 0