URLConnection
URLConnection類使用
URLConnection實(shí)例類獲取指定首部信息
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個(gè)首部段的值
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訪問的頁面應(yīng)該緩存。使用HTTPS和POST的不緩存包雀。
HTTP控制緩存的首部:
(1) Expires(HTTP 1.0) 緩存直到指定的時(shí)間
(2) Cache-control(HTTP 1.1) 會(huì)覆蓋Expires
- max-age=[seconds]
- s-maxage=[seconds] 在共享緩存的時(shí)間
- public : 可以緩存經(jīng)過認(rèn)證的響應(yīng)
- private : 單個(gè)用戶緩存可以保存憋他。共享緩存不保存孩饼。
- no-cache : 仍可以緩存。有附加條件竹挡,用Etag或Last-modified首部重新驗(yàn)證響應(yīng)的狀態(tài)镀娶。
- 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即默認(rèn)策略
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;}
}
向服務(wù)器寫入數(shù)據(jù)
//URLConnection方法梯码,獲取輸出流宝泵。
public OutputStream getOutputStream()
//默認(rèn)情況URLConnection不允許輸出,所以先要setDoOutput(true).請(qǐng)求方法將由GET變?yōu)镻OST
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;
}
//提交表單數(shù)據(jù)
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發(fā)送儿奶,
//我們只需發(fā)送數(shù)據(jù)。
out.write(query.toString());
out.write("\r\n");
//刷新并關(guān)閉流鳄抒,try語句保證關(guān)閉闯捎。沒關(guān)閉不會(huì)發(fā)送任何數(shù)據(jù)。
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");
}
}
}