• Java-URLConnection类详解


    抽象类 URLConnection 是所有类的超类,它代表应用程序和 URL 之间的通信链接。此类的实例可用于读取和写入此 URL 引用的资源。通常,创建一个到 URL 的连接需要几个步骤:

    openConnection()
        对影响到远程资源连接的参数进行操作。
    connect()
        与资源交互;查询头字段和内容。
    1. 通过在 URL 上调用 openConnection 方法创建连接对象。
    2. 操作设置参数和一般请求属性。
    3. 使用 connect 方法建立到远程对象的实际连接。
    4. 远程对象变为可用。远程对象的头字段和内容变为可访问。
    import java.net.*;
    import java.io.*;
    import java.util.Date;
    
    public class URLConnectionDemo {
         public static void main(String[] args) throws Exception{
    //         URLConnectionDemo urlconnectiondemo = new URLConnectionDemo();
                 int c;
                 URL hp=new URL("http://www.hao123.com/");
                 URLConnection hpCon=hp.openConnection();
                 System.out.println("Date: "+new Date(hpCon.getDate()));
                 System.out.println("Content-Type: "+hpCon.getContentType());
                 System.out.println("Expires: "+hpCon.getExpiration());
                 System.out.println("Last-Modified: "+ new Date(hpCon.getLastModified()));
                 int len=hpCon.getContentLength();
                 System.out.println("Content-Length: "+len);
                 if (len>0) {
                     System.out.println("=== content ===");
                     InputStream input=hpCon.getInputStream();
                     int i=len;
                     while ((c=input.read())!=-1 && (--i>0)) {
                         System.out.print((char)c);
                     }
                 }
                   else
                       System.out.println("No Content Available!");
                 }          
         }

    运行结果:

    Date: Mon Aug 27 11:07:02 CST 2007
    
    Content-Type: text/html
    
    Expires: 1188443222000
    
    Last-Modified: Fri Aug 24 12:29:00 CST 2007
    
    Content-Length: 44966
    
    === content ===
    
    <html><head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
    ……
  • 相关阅读:
    abp vnext v2.9.0 Blogging模块安装遇到的问题及解决方法
    TestCafe前端E2E自动化测试技术要点(转)
    UI自动化测试框架 ---TestCafe(转)
    一条龙(1)
    Nginx常用命令
    如何下载各大视频网站的视频,从html5中video标签截取blob视频流(纯使用Downie下载工具非代码操作)
    beego连接Mysql,生成WebAPI+CRUD和Swagger
    Go每日一题(7)
    Go每日一题(6)
    Go每日一题(5)
  • 原文地址:https://www.cnblogs.com/hwaggLee/p/4940018.html
Copyright © 2020-2023  润新知