您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
javase第三季学习笔记-URL
发布时间:2017-08-10 15:27:44编辑:雪饮阅读()
URL概述
• public final class URL extends Object implements Serializable
• URL(uniform resource location )类 URL 代表一个统一资源定位符,它是指向互联网“资源”的指针。
• URL(String spec)
根据 String 表示形式创建 URL 对象。
• URLConnection openConnection()
返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。
• String getHost()
获取此 URL 的主机名(如果适用)。
• String getPath()
获取此 URL 的路径部分。
• int getPort()
获取此 URL 的端口号。
• String getProtocol()
获取此 URL 的协议名称。
URLConnection
• public abstract class URL Connection extends Object
• 抽象类 URLConnection 是所有类的超类,它代表应用程序和 URL 之间的通信链接。
• InputStream getInputStream()
返回从此打开的连接读取的输入流。
• OutputStream getOutputStream()
返回写入到此连接的输出流。
示例代码:
package com.vince.url;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class URLDemo {
public static void main(String[] args) throws IOException {
//根据网址构造url对象
URL url=new URL("http://www.gaojiupan.cn/e/data/images/notimg.gif");
System.out.println("主机名:"+url.getHost());
System.out.println("资源路径:"+url.getPath());
System.out.println("端口号:"+url.getPort());
System.out.println("协议:"+url.getProtocol());
//通过url打开连接
URLConnection conn=url.openConnection();
//获取连接的输入流对象
BufferedInputStream bis=new BufferedInputStream(conn.getInputStream());
//构造文件输出流对象
String path="E:"+File.separator+"duminjie"+File.separator+"notimg.gif";
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(path));
byte[] bytes=new byte[1024*10];
int len=-1;
while((len=bis.read(bytes))!=-1){
bos.write(bytes,0,len);
bos.flush();
}
bos.close();
bis.close();
System.out.println("下载完成");
}
}
URLEncoder
• public class URLEncoder extends Object
• HTML 格式编码的实用工具类。该类包含了将 String 转换为 application/x-www-form-urlencoded MIME 格式的静态方法。
• static String encode(String s, String enc)
使用指定的编码机制将字符串转换为 application/x-www-form-urlencoded 格式。
URLDecoder
• public class URLDecoder extends Object
• HTML 格式解码的实用工具类。该类包含了将 String 从 application/x-www-form-urlencoded MIME 格式解码的静态方法。
static String decode(String s, String enc)
示例代码:
package com.vince.url;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
public class URLDemo2 {
public static void main(String[] args) throws UnsupportedEncodingException {
String url="http://www.gaojiupan.cn/index.php?username=雪饮&password=duminjie";
//把url地址进行编码
url=URLEncoder.encode(url,"UTF-8");
System.out.println(url);
//把url地址进行解码
url=URLDecoder.decode(url,"UTF-8");
System.out.println(url);
}
}
关键字词:javase,URL