HTTP URLConnection

========================= URLConnection=============================
URLConnection类是以Socket为底的更高层的类,其实它主要面向HTTP协议,通过该类可以获得响应Http的头信息及设置客户端HTTP的请求消息头,总之它于HTTP的对应关系如下:
获取响应头(URLConnection):
getResponseCode
getResponseMessage
String getHeaderField(int n)
String getContentEncoding()
int getContentLength()  
String getContentType()  
long getDate()
获取响应正文:
URLConnection.getInputStream().read()
设置请求头:
void setRequestMethod(String method) //可以为GET/POST/DELETE等
void setRequestProperty(String key, String value) //可调用多次  
当用POST方式发送请求时可以有实体正文,设置方法:
URLConnection.getOutputStream().write()
构造函数是保护的不能用,一般是这样提到 URLConnection对象
try {
  URL u = new URL("http://www.greenpeace.org/");
  URLConnection uc = u.openConnection( );
}
catch (MalformedURLException ex) {
  System.err.println(ex);
}
catch (IOException ex) {
  System.err.println(ex);
}
读数据的方法:
URL u = new URL(args[0]);
URLConnection uc = u.openConnection( );
InputStream raw = uc.getInputStream( );
InputStream buffer = new BufferedInputStream(raw);  
获取头信息:(特别是HTTP协议)
HTTP/1.1 200 OK
Date: Mon, 18 Oct 1999 20:06:48 GMT
Server: Apache/1.3.4 (Unix) PHP/3.0.6 mod_perl/1.17
Last-Modified: Mon, 18 Oct 1999 12:58:21 GMT
ETag: "1e05f2-89bb-380b196d"
Accept-Ranges: bytes
Content-Length: 35259
Connection: close
Content-Type: text/html

public String getContentType( )
public int getContentLength( )
public String getContentEncoding( )
public long getDate( )
public long getExpiration( )
public long getLastModified( )

//任意头字段
public String getHeaderField(String name)
//Content-Type:text/html  下面的方法返回 Content-Type
public String getHeaderFieldKey(int n)
//这个返回text/html部分
public String getHeaderField(int n)
//获取日期的同时转换为long型
public long getHeaderFieldDate(String name, long default)
//获取字段的同时转换为int 型
public int getHeaderFieldInt(String name, int default)


HTTP消息头:
分为通用消息头(请求/响应均可用)、请求消息头、响应消息头、实体消息头
通用消息头:
Cache-Control  用于控制代理服务器的缓存方式
Connection 是否一直保持连接 Http1.1的默认方式
Data: 表示时间

请求头:
Accept: text/html,image/*
Accept-Charset: ISO-8859-1,unicode-1-1
Accept-Encoding: gzip,compress //对应于相应消息的Content-Encoding
Accept-Language: en-gb,zh-cn
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值