Netty源码解析之 java网络编程篇(4)

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");
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文是《图解HTTP》读书笔记的第二篇,主要包括此书的第六章内容,因为第六章的内容较多,而且比较重要,所以单独写为...
    lijiankun24阅读 1,399评论 0 6
  • 本文内容大多参考《图解HTTP》一书 一. 认识代理服务器 所以讲缓存为什么要先扯代理服务器?别急,让我们看一下一...
    流光号船长阅读 1,969评论 0 10
  • okhhtp缓存篇_上# 注:本文分析的基础是在大概了解了okhhtp的基础上分析的如果不了解的话建议看下okhh...
    愿来缘来阅读 1,106评论 0 2
  • HTTP 首部 HTTP 报文首部 HTTP 协议的请求和响应报文中必定包含 HTTP 首部。首部内容为客 户端和...
    Gu_Ran阅读 778评论 0 3
  • 这一个月看着孩子的成绩直线下降,原来的原则是否要坚持,能看到一些曙光吗?心里一片茫茫然。漠视他不交作业吗?还是表...
    安静的大海阅读 128评论 0 0