zoukankan      html  css  js  c++  java
  • JavaSE: URL类 / URLConnection类

    URL类(熟悉)

    1.  基本概念

      <1>  java.net.URL (Uniform Resource Identifier)类:用于表示统一的资源定位器,也就是指向万维网上“资源”的指针。

          (资源可以是简单的文件和目录,也可以是对复杂对象的引用,例如,对数据库或搜索引擎的查询等) 

      <2>  通过URL可以访问万维网上的网络资源,最常见的是 www 和 ftp站点, 浏览器通过解析给定的 URL 可以在网络上查找相应的资源

      <3>  URL的基本结构如下:

            <传输协议>://<主机名>:<端口号>/<资源地址> 

    2.  常用的方法

    方法声明 功能介绍
    URL(String spec) 根据参数指定的字符串,信息构造对象
    String getProtocol() 获取协议名称
    String getHost() 获取主机名称
    int getPort() 获取端口号
    String getPath() 获取路径信息
    String getFile() 获取文件名
    URLConnection openConnection() 获取URLConnection类的实例

    URLConnection类

    1.  基本概念

        java.net.URLConnection类是个抽象类,该类表示应用程序和URL之间的通信连接的所有类的超类,主要实现类有支持HTTP特有功能的HttpURLConnection类

    2.  HttpURLConnection类的常用方法

        方法声明                           功能介绍

        InputStream getInputStream()                 获取输入流

        void disconnect()                         断开连接

     1 class URLTest {
     2     main(){
     3         try{
     4             //    1.    使用参数指定的字符串,来构造对象
     5             URL url = new URL("https://www.cnblogs.com/JasperZhao/");
     6 
     7             //    2.    获取相关信息,并打印出来
     8             System.out.println("获取到的协议名称是:" + url.getProtocol());
     9             System.out.println("获取到的主机名称是:" + url.getHost());
    10             System.out.println("获取到的端口号是:" + url.getPort());
    11 
    12             // 3.    建立连接并读取相关信息打印出来
    13             HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    14             InputStream inputStream = urlConnection.getInputStream();
    15             BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
    16             String str = null;
    17             while ((str = br.readLine()) != null) {
    18                 System.out.println(str);
    19             }
    20             br.close();
    21             // 断开连接
    22             urlConnection.disconnect();
    23 
    24         } catch (MalformedURLException e) {
    25             e.printStackTrace();
    26         } catch (IException e) {
    27             e.printStackTrace();
    28         }
    29 
    30     }
    31 }

    网络编程 - 练习

  • 相关阅读:
    SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"
    Tomcat跨域
    Invalid bean definition with name 'dataSource' defined in class path resource [applicationContext.xml]
    网速测试
    程序员实用工具网站
    安装wls报(主清单位置 "/u01/app/oracle/inventory" 无效 (无法读取/写入/执行))
    pom.xml
    CUDA -- 内存分配
    最长上升子序列(LIS: Longest Increasing Subsequence)
    实例化渲染
  • 原文地址:https://www.cnblogs.com/JasperZhao/p/14886166.html
Copyright © 2011-2022 走看看