okhttp中的Builder模式
阿新 • • 發佈:2021-08-05
程式碼
我們以Request類為例,以下是部分程式碼:
public final class Request { private final HttpUrl url; private final String method; private final Headers headers; private final RequestBody body; private final Object tag; private volatile CacheControl cacheControl; // Lazily initialized. private Request(Builder builder) { this.url = builder.url; this.method = builder.method; this.headers = builder.headers.build(); this.body = builder.body; this.tag = builder.tag != null ? builder.tag : this; } public static class Builder { private HttpUrl url; private String method; private Headers.Builder headers; private RequestBody body; private Object tag; public Builder() { this.method = "GET"; this.headers = new Headers.Builder(); } public Builder url(String url) { if (url == null) throw new NullPointerException("url == null"); // Silently replace websocket URLs with HTTP URLs. if (url.regionMatches(true, 0, "ws:", 0, 3)) { url = "http:" + url.substring(3); } else if (url.regionMatches(true, 0, "wss:", 0, 4)) { url = "https:" + url.substring(4); } HttpUrl parsed = HttpUrl.parse(url); if (parsed == null) throw new IllegalArgumentException("unexpected url: " + url); return url(parsed); } public Builder get() { return method("GET", null); } public Builder method(String method, RequestBody body) { if (method == null) throw new NullPointerException("method == null"); if (method.length() == 0) throw new IllegalArgumentException("method.length() == 0"); if (body != null && !HttpMethod.permitsRequestBody(method)) { throw new IllegalArgumentException("method " + method + " must not have a request body."); } if (body == null && HttpMethod.requiresRequestBody(method)) { throw new IllegalArgumentException("method " + method + " must have a request body."); } this.method = method; this.body = body; return this; } public Request build() { if (url == null) throw new IllegalStateException("url == null"); return new Request(this); } } }
source:https://github.com/square/okhttp/blob/parent-3.3.1/okhttp/src/main/java/okhttp3/Request.java
說明
Request類兩個明顯特點:
- 建構函式是私有的,只能通過類的內部呼叫,我們看到是Build方法呼叫
- 有個靜態的內部類Builder,構建Request例項只能通過Builder
使用
Request request = new Request.Builder() .get() .url("https:www.baidu.com") .build();