java网络编程-URLConnection

  • URLConnection是一个抽象类,表示指向URL指定资源的活动连接

1:打开URLConnection

  • 构造一个URL对象
  • 调用这个对象的openCoonnection(),获取URLConnection对象
  • 配置这个URLConnection
  • 读取首部字段
  • 获取输入输出流读写数据
  • 关闭连接

其中后面的一些步骤使无需 实现的,默认配置即可。

  • URLConnection没有公有构造函数,处理派生子类实现构造函数外,只能通过URL来获得URLConnection
     URL url=new URL("http://www.overcomingbias.com/");
       URLConnection urlConnection=url.openConnection();

2:读取服务器的数据

  • 要用字符流,不然会乱码的。
     URL url=new URL("http://www.baidu.com");
       URLConnection urlConnection=url.openConnection();
       InputStream in=urlConnection.getInputStream();
       BufferedInputStream bufferedInputStream=new BufferedInputStream(in);
       Reader reader=new InputStreamReader(bufferedInputStream);
       int re;
       while ((re=reader.read())!=-1){
           System.out.print((char)re);
       }

3:读取首部

3.1:获取特定首部

content-type

用于获取mime内容类型

什么是mime

  • 使用getconnect_type()方法
    返回内容类型,例如text/html,
    是文本数据可能还会返回编码方式,也可能不返回
   URL url=new URL("http://www.baidu.com");
       URLConnection urlConnection=url.openConnection();
        System.out.println(urlConnection.getContentType());

》》》text/html

Connect-length

  • 内容一共有多少字节,如果没有这个首部就返回-1;
  • 内容大小超过int的范围,20亿左右也会返回-1
 URL url=new URL("http://www.baidu.com");
       URLConnection urlConnection=url.openConnection();
       System.out.println(urlConnection.getContentLength());
>>>2381

Connect-coding

  • 返回文本的编码方式
  • 没有编码方式就返回null,
  • 使用getContentEncoding();
  • 与乱码的编码好像无关

3.2:获取任意首部

  • getHeaderField(String name);返回一个字符串
  • getHearderFieldKey(int n);第n个首部名称,没了返回null
  • getHearderField(int n);第n个首部的值
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值