URL

package com.itheima.url;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class UrlDemo {

public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
    URL url = new URL("http://e.hiphotos.baidu.com/album/w%3D2048/sign=9b7795ff0b55b3199cf9857577918026/4d086e061d950a7b36bc973a0bd162d9f3d3c947.jpg");
    System.out.println("主机名:" + url.getHost());
    System.out.println("资源路径" + url .getPath());
    System.out.println("端口号:" + url.getPort());
    System.out.println("协议名称:" + url.getProtocol());
    //通过Url打开连接
    URLConnection connection = url.openConnection();
    //截取文件名
    String filename = url.getPath().substring(url.getPath().lastIndexOf("/"));
    //获取连接的输入流对象
    InputStream is = connection.getInputStream();
    BufferedInputStream bis = new BufferedInputStream(is);
    //通过输入流对象构造输出流对象
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\" + filename));
    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("下载完成");
}

}

package com.itheima.url;

import java.net.URLDecoder;
import java.net.URLEncoder;

/**
* url地址编码与解码
* @author Administrator
*
*/
public class URLDemo2 {

public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
    String url  = "http://www.baidu.com/username=小白&password=123";
    //把url地址编码为UTF-8格式
    url = URLEncoder.encode(url, "UTF-8");
    System.out.println(url);
    //把url进行解码
    url = URLDecoder.decode(url, "UTF-8");
    System.out.println(url);
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值