zoukankan      html  css  js  c++  java
  • 【JAVA网络流之URL】

    一、URL

    URL对象可以认为是URLConnection对象+Socket对象。

    Java.lang.Object

             |-Java.net.URL

    常用构造方法:

    URL(String spec)
              根据 String 表示形式创建 URL 对象。

    常用方法:

     URLConnection

    openConnection()
              返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。

    URLConnection

    openConnection(Proxy proxy)
              
    与 openConnection() 类似,所不同是连接通过指定的代理建立;不支持代理方式的协议处理程序将忽略该代理参数并建立正常的连接。

    InputStream

    openStream()
              
    打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream

    二、URLConnection

    Java.lang.Object

             |-java.net.URLConnection

    构造方法:

    protected

    URLConnection(URL url)
              构造一个到指定 URL 的 URL 连接。

    常用方法:

     InputStream

    getInputStream()
              返回从此打开的连接读取的输入流。

     OutputStream

    getOutputStream()
              
    返回写入到此连接的输出流。

     URL

    getURL()
              
    返回此 URLConnectionURL 字段的值。

     三、使用URL获取网页内容

    使用的服务器:Apache

    代码:

     1 package p08.URLDemo.p01.URLDemo;
     2 
     3 import java.io.BufferedReader;
     4 import java.io.IOException;
     5 import java.io.InputStream;
     6 import java.io.InputStreamReader;
     7 import java.net.URL;
     8 import java.net.URLConnection;
     9 
    10 public class URLObjectDemo01 {
    11     public static void main(String args[]) throws IOException
    12     {
    13         /**
    14          * URL对象实际上是URLConnection对象+Socket对象
    15          */
    16         URL url=new URL("http"+ "://192.168.209.1:80//myWeb/index.html?name=zhangsan");
    17         URLConnection urslc=url.openConnection();
    18         InputStream is=urslc.getInputStream();
    19         //两句可以合并成InputStream is=url.openStream();
    20         InputStreamReader isr=new InputStreamReader(is);
    21         BufferedReader br=new BufferedReader(isr);
    22         String str=null;
    23         while((str=br.readLine())!=null)
    24         { 
    25             System.out.println(str+System.getProperty("line.separator"));
    26         }
    27         br.close();
    28     }
    29 }
    View Code

    运行结果:

    相对于使用Socket,这里省略了开始行与首部行,只有实体主体部分

  • 相关阅读:
    docker搭建本地仓库并制作自己的镜像
    docker命令及操作
    从零开始学android开发-项目打包发布
    从零开始学android开发-adt-bundle-eclipse下的修改android app名称
    从零开始学android开发-项目重命名
    Android Studio系列教程一--下载与安装
    Axure RP 7.0注册码
    MVC网站发布常见问题
    无间断滚动的新闻文章列表
    @HTML
  • 原文地址:https://www.cnblogs.com/kuangdaoyizhimei/p/4238510.html
Copyright © 2011-2022 走看看