添加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")); } }
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();
Request request = new Request.Builder() .cacheControl(new CacheControl.Builder().noCache().build()) .url(url) .build();
// 等同於 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();
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. }