网络编程(七)URL下载网络资源

网络编程(七)URL下载网络资源

URL

URL组成

  • 统一资源定位符:定位资源,定位互联网上的某一个资源

  • DNS域名解析:把一个域名(www.baidu.com)变成一个IP

    /*
    url的组成:
    协议://ip地址:端口/项目名/资源
    */
    

URL方法

Modifier and Type Method and Description
boolean equals(Object obj) 将此URL与其他对象进行比较。
String getAuthority() 获取此的授权部分 URL
Object getContent() 获取此URL的内容。
Object getContent(类[] classes) 获取此URL的内容。
int getDefaultPort() 获取与此 URL的协议的默认端口号。
String getFile() 获取此 URL的文件名。
String getHost() 获取此 URL的主机名(如适用)。
String getPath() 获取此 URL的路径部分。
int getPort() 获取此 URL的端口号。
String getProtocol() 获取此 URL的协议名称。
String getQuery() 获取此 URL的查询部分。参数
String getRef() 获取此的锚定(也称为“参考”) URL
String getUserInfo() 获取该 URL的userInfo部分。
int hashCode() 创建适合哈希表索引的整数。
URLConnection openConnection() 返回一个URLConnection实例,表示与URL引用的远程对象的URL
URLConnection openConnection(Proxy proxy)openConnection()相同,但连接将通过指定的代理进行; 不支持代理的协议处理程序将忽略代理参数并进行正常连接。
InputStream openStream() 打开与此 URL ,并返回一个 InputStream ,以便从该连接读取。
boolean sameFile(URL other) 比较两个URL,不包括片段组件。
static void setURLStreamHandlerFactory(URLStreamHandlerFactory fac) 设置应用程序的 URLStreamHandlerFactory
String toExternalForm() 构造这个 URL的字符串 URL
String toString() 构造此 URL的字符串表示 URL
URI toURI() 返回相当于此URL的URI

常用方法

String getFile() 获取此 URL的文件名。
String getHost() 获取此 URL的主机名(如适用)。
String getPath() 获取此 URL的路径部分。
int getPort() 获取此 URL的端口号。
String getProtocol() 获取此 URL的协议名称。
String getQuery() 获取此 URL的查询部分,参数。

URL下载代码实例

public class URLDemo01 {
    public static void main(String[] args) throws Exception{
        //1.下载地址
        URL url = new URL("http://localhost:8080/sxp/123ad.txt");
        //2.连接到这个资源 HTTP
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
        InputStream inputStream =urlConnection.getInputStream();
        FileOutputStream fos=new FileOutputStream("123ad.txt");
        byte[] buffer=new byte[1024];
        int len;
        while ((len=inputStream.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
        fos.close();
        inputStream.close();
        urlConnection.disconnect();//断开连接
    }
}
posted @   史小鹏  阅读(95)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示