Home | 簡體中文 | 繁體中文 | 雜文 | 打賞(Donations) | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 知乎專欄 | Search | About

18.6. http header 相關設置

18.6.1. 設置 HTTP 頭

添加Http頭

			
Request request = new Request.Builder()
        .url(url)
        .addHeader("CLIENT", "AD")
        .addHeader("USERID", "343")
        .build();		
			
			

覆蓋 HTTP 頭

			
        Request request = new Request.Builder()
                .header("Authorization", "replace this text with your token")
                .url(url)
                .build();		
			
			
			
public class Headers {
   public static void main(String[] args) throws IOException {
    OkHttpClient client = new OkHttpClient();
 
    Request request = new Request.Builder()
            .url("http://www.netkiller.cn")
            .header("User-Agent", "Apple Mac")
            .addHeader("Accept", "text/html")
            .build();
 
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) {
        throw new IOException("伺服器端錯誤: " + response);
    }
 
    System.out.println(response.header("Server"));
    System.out.println(response.headers("Set-Cookie"));
   }
}		
			
			

18.6.2. Cookie 管理

			
OkHttpClient mHttpClient = new OkHttpClient.Builder().cookieJar(new CookieJar() {
    private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
    @Override
    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
        cookieStore.put(url.host(), cookies);
    }
    @Override
    public List<Cookie> loadForRequest(HttpUrl url) {
        List<Cookie> cookies = cookieStore.get(url.host());
        return cookies != null ? cookies : new ArrayList<Cookie>();
    }
}).build();			
			
			

18.6.3. 禁用緩存

			
Request request = new Request.Builder()
    .cacheControl(new CacheControl.Builder().noCache().build())
    .url(url)
    .build();			
			
			

18.6.4. 設置緩存 max-age

			
// 等同於 nocache			
Request request = new Request.Builder()
    .cacheControl(new CacheControl.Builder()
        .maxAge(0, TimeUnit.SECONDS)
        .build())
    .url("https://www.netkiller.cn")
    .build();
    
// 設置緩存 365 天
Request request = new Request.Builder()
    .cacheControl(new CacheControl.Builder()
        .maxStale(365, TimeUnit.DAYS)
        .build())
    .url("https://www.netkiller.cn")
    .build();    	
			
			

18.6.5. 強制緩存

			
Request request = new Request.Builder()
    .cacheControl(new CacheControl.Builder()
        .onlyIfCached()
        .build())
    .url("https://www.netkiller.cn/helloworld.txt")
    .build();
Response forceCacheResponse = client.newCall(request).execute();
if (forceCacheResponse.code() != 504) {
  // The resource was cached! Show it.
} else {
  // The resource was not cached.
}