URLConnection
URLConnection类使用
URLConnection实例类获取指定首部信息
public String getContentType()
public int getContentLength()
public String getContentEncoding()
public long getDate()
public long getExpiration()
public long getLastModified()
package Ch7;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class AllHeaders {
public static void main(String[] args) {
for(int i=0; i<args.length; i++){
try{
URL u = new URL(args[i]);
URLConnection uc = u.openConnection();
for(int j=1;;j++){
//getHeaderField(String name),返回指定类型首部段的值
//getHeaderField(int n),返回第n个首部段的值
String header = uc.getHeaderField(j);
if(header==null) break;
System.out.println(uc.getHeaderFieldKey(j)+":"+header);
}
}catch (MalformedURLException ex){
System.out.println(args[i]+"is not a URL I understand");
}catch (IOException ex){
System.err.println(ex);
}
System.out.println();
}
}
}
/*Server:Apache
Location:https://www.oreilly.com/
Content-Length:232
Content-Type:text/html; charset=iso-8859-1
Cache-Control:max-age=1316
Expires:Wed, 29 Nov 2017 05:37:00 GMT
Date:Wed, 29 Nov 2017 05:15:04 GMT
Connection:keep-alive
*/
获取任意首部子段
pubilc String getHeaderField(String name)
public String getHeaderFieldKey(int n)
public String getHeaderField(int n)
public long getHeaderFieldDate(String name, long default)
public int getHeaderFieldInt(String name , int default)
缓存
一般情况,使用GET通过HTTP访问的页面应该缓存。使用HTTPS和POST的不缓存。
HTTP控制缓存的首部:
(1) Expires(HTTP 1.0) 缓存直到指定的时间
(2) Cache-control(HTTP 1.1) 会覆盖Expires
- max-age=[seconds]
- s-maxage=[seconds] 在共享缓存的时间
- public : 可以缓存经过认证的响应
- private : 单个用户缓存可以保存。共享缓存不保存。
- no-cache : 仍可以缓存。有附加条件,用Etag或Last-modified首部重新验证响应的状态。
- no-store : 无论如何,都不缓存。
package Ch7;
import java.util.Date;
import java.util.Locale;
public class CacheControl {
private Date maxAge = null;
private Date sMaxAge = null;
private boolean mustRevalidate = false;
private boolean nocache = false;
private boolean nostore = false;
private boolean proxyRevalidate = false;
private boolean publicCache = false;
private boolean privateCache = false;
public CacheControl(String s) {
//没有cach-control即默认策略
if (s==null||!s.contains(":")){
return;}
//取得值
String value = s.split(":")[1].trim();
String[] components = value.split(",");
Date now = new Date();
for(String component: components){
try{
component = component.trim().toLowerCase(Locale.US);
if(component.startsWith("max-age=")){
int secondsInTheFuture = Integer.parseInt(component.substring(8));
maxAge = new Date(now.getTime()+1000*secondsInTheFuture);
}else if(component.startsWith("s-maxage=")){
int secondsInTheFuture = Integer.parseInt(component.substring(8));
sMaxAge = new Date(now.getTime()+1000*secondsInTheFuture);
} else if(component.equals("must-revalidate")){
mustRevalidate = true;
} else if(component.equals("proxy-revalidate")){
proxyRevalidate = true;
} else if(component.equals("no-cache")){
nocache = true;
}else if(component.equals("public")){
publicCache= true;
}else if(component.equals("private")){
privateCache= true;
}
}catch (RuntimeException ex){
continue;
}
}
}
public Date getMaxAge(){
return maxAge;}
public Date getSharedMaxAge(){
return sMaxAge;}
public boolean mustRevalidate(){
return mustRevalidate;}
public boolean ProxyRevalidate(){
return proxyRevalidate;}
public boolean noStore(){
return nostore;}
public boolean noCache(){
return nocache;}
public boolean PublicCache(){
return publicCache;}
public boolean PrivateCache(){
return privateCache;}
}
向服务器写入数据
//URLConnection方法,获取输出流。
public OutputStream getOutputStream()
//默认情况URLConnection不允许输出,所以先要setDoOutput(true).请求方法将由GET变为POST
package Ch7;
import Ch4.QueryString;
import java.net.*;
import java.io.*;
public class FormPoster {
private URL url;
private QueryString query = new QueryString();
public FormPoster (URL url){
if(!url.getProtocol().toLowerCase().startsWith("http")){
throw new IllegalArgumentException("Posting only works for http URLS");
}
this.url = url;
}
public void add(String name, String value) throws UnsupportedEncodingException{
query.add(name,value);
}
public URL getURL(){
return this.url;
}
//提交表单数据
public InputStream post() throws IOException{
URLConnection uc = url.openConnection();
uc.setDoOutput(true);
try(OutputStreamWriter out = new OutputStreamWriter(uc.getOutputStream(),"UTF-8")){
//POST行、Content-type首部和Content-length首部
//由URLConnection发送,
//我们只需发送数据。
out.write(query.toString());
out.write("\r\n");
//刷新并关闭流,try语句保证关闭。没关闭不会发送任何数据。
out.flush();
}
return uc.getInputStream();
}
public static void main(String[] args) throws UnsupportedEncodingException{
URL url;
if(args.length>0){
try{
url = new URL(args[0]);
}catch (MalformedURLException ex){
System.err.println("Usage: java FormPoster url");
return;
}
}else {
try{
url = new URL("http://www.cafeaulait.org/books/jnp4/postquery.phtml");
}catch (MalformedURLException ex){
System.err.println(ex);
return;
}
}
FormPoster poster = new FormPoster(url);
poster.add("name","Elliotte Rusty Harold");
poster.add("email","elharo@ibiblio.org");
try(InputStream in = poster.post()){
Reader r = new InputStreamReader(in);
int c;
while((c=r.read())!=-1){
System.out.print((char)c);
}
System.out.println();
}catch (IOException ex){
System.err.println("ex");
}
}
}