Commit f8cf07a7 authored by 王雷's avatar 王雷

移除无用代码

parent f503fe06
...@@ -6,6 +6,7 @@ import androidx.lifecycle.OnLifecycleEvent ...@@ -6,6 +6,7 @@ import androidx.lifecycle.OnLifecycleEvent
import com.dhh.websocket.Config import com.dhh.websocket.Config
import com.dhh.websocket.RxWebSocket import com.dhh.websocket.RxWebSocket
import com.dhh.websocket.WebSocketSubscriber import com.dhh.websocket.WebSocketSubscriber
import okhttp3.WebSocket
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
/** /**
...@@ -22,7 +23,7 @@ class SocketHelper : LifecycleObserver { ...@@ -22,7 +23,7 @@ class SocketHelper : LifecycleObserver {
super.onError(e) super.onError(e)
} }
override fun onOpen(webSocket: okhttp4.WebSocket) { override fun onOpen(webSocket: WebSocket) {
super.onOpen(webSocket) super.onOpen(webSocket)
} }
......
...@@ -102,7 +102,7 @@ task generateSourcesJar(type: Jar) { ...@@ -102,7 +102,7 @@ task generateSourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs from android.sourceSets.main.java.srcDirs
classifier 'sources' classifier 'sources'
} }
def versionName = '1.0.0' def versionName = '1.0.1'
def SNAPSHOT_REPOSITORY_URL = "https://hub.zmcms.cn/repository/maven-snapshots/" def SNAPSHOT_REPOSITORY_URL = "https://hub.zmcms.cn/repository/maven-snapshots/"
def RELEASE_REPOSITORY_URL = "https://hub.zmcms.cn/repository/maven-releases/" def RELEASE_REPOSITORY_URL = "https://hub.zmcms.cn/repository/maven-releases/"
......
...@@ -5,7 +5,7 @@ import java.util.concurrent.TimeUnit; ...@@ -5,7 +5,7 @@ import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager; import javax.net.ssl.X509TrustManager;
import okhttp4.OkHttpClient; import okhttp3.OkHttpClient;
public final class Config { public final class Config {
protected long reconnectInterval = 1; protected long reconnectInterval = 1;
......
...@@ -22,11 +22,11 @@ import io.reactivex.functions.Consumer; ...@@ -22,11 +22,11 @@ import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function; import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate; import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers; import io.reactivex.schedulers.Schedulers;
import okhttp4.OkHttpClient; import okhttp3.OkHttpClient;
import okhttp4.Request; import okhttp3.Request;
import okhttp4.Response; import okhttp3.Response;
import okhttp4.WebSocket; import okhttp3.WebSocket;
import okhttp4.WebSocketListener; import okhttp3.WebSocketListener;
import okio.ByteString; import okio.ByteString;
@Deprecated @Deprecated
...@@ -44,7 +44,7 @@ public class RxWebSocketUtil { ...@@ -44,7 +44,7 @@ public class RxWebSocketUtil {
private RxWebSocketUtil() { private RxWebSocketUtil() {
try { try {
Class.forName("okhttp4.OkHttpClient"); Class.forName("okhttp3.OkHttpClient");
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
throw new RuntimeException("Must be dependency okhttp3 !"); throw new RuntimeException("Must be dependency okhttp3 !");
} }
......
...@@ -4,7 +4,7 @@ import androidx.annotation.CallSuper; ...@@ -4,7 +4,7 @@ import androidx.annotation.CallSuper;
import io.reactivex.annotations.NonNull; import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer; import io.reactivex.functions.Consumer;
import okhttp4.WebSocket; import okhttp3.WebSocket;
import okio.ByteString; import okio.ByteString;
@Deprecated @Deprecated
public abstract class WebSocketConsumer implements Consumer<WebSocketInfo> { public abstract class WebSocketConsumer implements Consumer<WebSocketInfo> {
......
...@@ -2,7 +2,7 @@ package com.zhimai.websocket; ...@@ -2,7 +2,7 @@ package com.zhimai.websocket;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import okhttp4.WebSocket; import okhttp3.WebSocket;
import okio.ByteString; import okio.ByteString;
public class WebSocketInfo { public class WebSocketInfo {
......
...@@ -3,7 +3,7 @@ package com.zhimai.websocket; ...@@ -3,7 +3,7 @@ package com.zhimai.websocket;
import io.reactivex.Observer; import io.reactivex.Observer;
import io.reactivex.annotations.NonNull; import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable; import io.reactivex.disposables.Disposable;
import okhttp4.WebSocket; import okhttp3.WebSocket;
import okio.ByteString; import okio.ByteString;
public abstract class WebSocketSubscriber implements Observer<WebSocketInfo> { public abstract class WebSocketSubscriber implements Observer<WebSocketInfo> {
......
...@@ -4,9 +4,9 @@ import android.os.Looper; ...@@ -4,9 +4,9 @@ import android.os.Looper;
import java.io.IOException; import java.io.IOException;
import okhttp4.Call; import okhttp3.Call;
import okhttp4.Callback; import okhttp3.Callback;
import okhttp4.Response; import okhttp3.Response;
public class CallbackToMainThread implements Callback { public class CallbackToMainThread implements Callback {
private MCallback mCallback = null; private MCallback mCallback = null;
......
...@@ -14,14 +14,14 @@ import java.util.Iterator; ...@@ -14,14 +14,14 @@ import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import okhttp4.Call; import okhttp3.Call;
import okhttp4.Callback; import okhttp3.Callback;
import okhttp4.ConnectionPool; import okhttp3.ConnectionPool;
import okhttp4.HttpUrl; import okhttp3.HttpUrl;
import okhttp4.OkHttpClient; import okhttp3.OkHttpClient;
import okhttp4.Request; import okhttp3.Request;
import okhttp4.RequestBody; import okhttp3.RequestBody;
import okhttp4.Response; import okhttp3.Response;
/** /**
* 新版本okhttp * 新版本okhttp
...@@ -280,7 +280,7 @@ public class MyOkHttpUtils { ...@@ -280,7 +280,7 @@ public class MyOkHttpUtils {
*/ */
private RequestBody setRequestBody(Map<String, String> BodyParams) { private RequestBody setRequestBody(Map<String, String> BodyParams) {
RequestBody body = null; RequestBody body = null;
okhttp4.FormBody.Builder formEncodingBuilder = new okhttp4.FormBody.Builder(); okhttp3.FormBody.Builder formEncodingBuilder = new okhttp3.FormBody.Builder();
if (BodyParams != null) { if (BodyParams != null) {
Iterator<String> iterator = BodyParams.keySet().iterator(); Iterator<String> iterator = BodyParams.keySet().iterator();
String key = ""; String key = "";
......
...@@ -7,12 +7,12 @@ import com.zhimai.websocket.util.Logger; ...@@ -7,12 +7,12 @@ import com.zhimai.websocket.util.Logger;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import okhttp4.Interceptor; import okhttp3.Interceptor;
import okhttp4.MediaType; import okhttp3.MediaType;
import okhttp4.Request; import okhttp3.Request;
import okhttp4.RequestBody; import okhttp3.RequestBody;
import okhttp4.Response; import okhttp3.Response;
import okhttp4.ResponseBody; import okhttp3.ResponseBody;
import okio.Buffer; import okio.Buffer;
public class NetworkIntercepter implements Interceptor { public class NetworkIntercepter implements Interceptor {
......
...@@ -3,9 +3,9 @@ package com.zhimai.websocket.http; ...@@ -3,9 +3,9 @@ package com.zhimai.websocket.http;
import java.io.IOException; import java.io.IOException;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import okhttp4.Interceptor; import okhttp3.Interceptor;
import okhttp4.Request; import okhttp3.Request;
import okhttp4.Response; import okhttp3.Response;
public class RetryIntercepter implements Interceptor { public class RetryIntercepter implements Interceptor {
public int maxRetryCount; public int maxRetryCount;
......
package com.zhimai.websocket.listener; package com.zhimai.websocket.listener;
import okhttp4.WebSocket; import okhttp3.WebSocket;
import okio.ByteString; import okio.ByteString;
public interface WebSocketSubscriberListener { public interface WebSocketSubscriberListener {
......
...@@ -25,7 +25,7 @@ import org.litepal.LitePal; ...@@ -25,7 +25,7 @@ import org.litepal.LitePal;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import io.reactivex.annotations.NonNull; import io.reactivex.annotations.NonNull;
import okhttp4.WebSocket; import okhttp3.WebSocket;
import okio.ByteString; import okio.ByteString;
/** /**
......
...@@ -17,7 +17,7 @@ import com.zhimai.websocket.listener.QueueMessageBackListener ...@@ -17,7 +17,7 @@ import com.zhimai.websocket.listener.QueueMessageBackListener
import com.zhimai.websocket.listener.SocketMessageBackListener import com.zhimai.websocket.listener.SocketMessageBackListener
import io.reactivex.annotations.NonNull import io.reactivex.annotations.NonNull
import okhttp4.WebSocket import okhttp3.WebSocket
import okio.ByteString import okio.ByteString
import org.json.JSONException import org.json.JSONException
import org.json.JSONObject import org.json.JSONObject
......
...@@ -33,8 +33,8 @@ import java.util.Map; ...@@ -33,8 +33,8 @@ import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import io.reactivex.annotations.NonNull; import io.reactivex.annotations.NonNull;
import okhttp4.RequestBody; import okhttp3.RequestBody;
import okhttp4.WebSocket; import okhttp3.WebSocket;
import okio.ByteString; import okio.ByteString;
/** /**
...@@ -739,7 +739,7 @@ public class MsgWebSocketUtil { ...@@ -739,7 +739,7 @@ public class MsgWebSocketUtil {
////////////// //////////////
RequestBody body = null; RequestBody body = null;
okhttp4.FormBody.Builder formEncodingBuilder = new okhttp4.FormBody.Builder(); okhttp3.FormBody.Builder formEncodingBuilder = new okhttp3.FormBody.Builder();
for (int i = 0; i < ls_tag.size(); i++) { for (int i = 0; i < ls_tag.size(); i++) {
formEncodingBuilder.add("tag[]", ls_tag.get(i).getTag()); formEncodingBuilder.add("tag[]", ls_tag.get(i).getTag());
} }
......
...@@ -2,7 +2,6 @@ package com.zhimai.websocket.util; ...@@ -2,7 +2,6 @@ package com.zhimai.websocket.util;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.util.Log;
/*** /***
......
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp4;
import static okhttp4.internal.Util.equal;
import java.net.Proxy;
import java.net.ProxySelector;
import java.util.List;
import androidx.annotation.Nullable;
import javax.net.SocketFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSocketFactory;
import okhttp4.internal.Util;
/**
* A specification for a connection to an origin server. For simple connections, this is the
* server's hostname and port. If an explicit proxy is requested (or {@linkplain Proxy#NO_PROXY no
* proxy} is explicitly requested), this also includes that proxy information. For secure
* connections the address also includes the SSL socket factory, hostname verifier, and certificate
* pinner.
*
* <p>HTTP requests that share the same {@code Address} may also share the same {@link Connection}.
*/
public final class Address {
final HttpUrl url;
final Dns dns;
final SocketFactory socketFactory;
final Authenticator proxyAuthenticator;
final List<Protocol> protocols;
final List<ConnectionSpec> connectionSpecs;
final ProxySelector proxySelector;
final @Nullable Proxy proxy;
final @Nullable SSLSocketFactory sslSocketFactory;
final @Nullable HostnameVerifier hostnameVerifier;
final @Nullable CertificatePinner certificatePinner;
public Address(String uriHost, int uriPort, Dns dns, SocketFactory socketFactory,
@Nullable SSLSocketFactory sslSocketFactory, @Nullable HostnameVerifier hostnameVerifier,
@Nullable CertificatePinner certificatePinner, Authenticator proxyAuthenticator,
@Nullable Proxy proxy, List<Protocol> protocols, List<ConnectionSpec> connectionSpecs,
ProxySelector proxySelector) {
this.url = new HttpUrl.Builder()
.scheme(sslSocketFactory != null ? "https" : "http")
.host(uriHost)
.port(uriPort)
.build();
if (dns == null) throw new NullPointerException("dns == null");
this.dns = dns;
if (socketFactory == null) throw new NullPointerException("socketFactory == null");
this.socketFactory = socketFactory;
if (proxyAuthenticator == null) {
throw new NullPointerException("proxyAuthenticator == null");
}
this.proxyAuthenticator = proxyAuthenticator;
if (protocols == null) throw new NullPointerException("protocols == null");
this.protocols = Util.immutableList(protocols);
if (connectionSpecs == null) throw new NullPointerException("connectionSpecs == null");
this.connectionSpecs = Util.immutableList(connectionSpecs);
if (proxySelector == null) throw new NullPointerException("proxySelector == null");
this.proxySelector = proxySelector;
this.proxy = proxy;
this.sslSocketFactory = sslSocketFactory;
this.hostnameVerifier = hostnameVerifier;
this.certificatePinner = certificatePinner;
}
/**
* Returns a URL with the hostname and port of the origin server. The path, query, and fragment of
* this URL are always empty, since they are not significant for planning a route.
*/
public HttpUrl url() {
return url;
}
/** Returns the service that will be used to resolve IP addresses for hostnames. */
public Dns dns() {
return dns;
}
/** Returns the socket factory for new connections. */
public SocketFactory socketFactory() {
return socketFactory;
}
/** Returns the client's proxy authenticator. */
public Authenticator proxyAuthenticator() {
return proxyAuthenticator;
}
/**
* Returns the protocols the client supports. This method always returns a non-null list that
* contains minimally {@link Protocol#HTTP_1_1}.
*/
public List<Protocol> protocols() {
return protocols;
}
public List<ConnectionSpec> connectionSpecs() {
return connectionSpecs;
}
/**
* Returns this address's proxy selector. Only used if the proxy is null. If none of this
* selector's proxies are reachable, a direct connection will be attempted.
*/
public ProxySelector proxySelector() {
return proxySelector;
}
/**
* Returns this address's explicitly-specified HTTP proxy, or null to delegate to the {@linkplain
* #proxySelector proxy selector}.
*/
public @Nullable Proxy proxy() {
return proxy;
}
/** Returns the SSL socket factory, or null if this is not an HTTPS address. */
public @Nullable SSLSocketFactory sslSocketFactory() {
return sslSocketFactory;
}
/** Returns the hostname verifier, or null if this is not an HTTPS address. */
public @Nullable HostnameVerifier hostnameVerifier() {
return hostnameVerifier;
}
/** Returns this address's certificate pinner, or null if this is not an HTTPS address. */
public @Nullable CertificatePinner certificatePinner() {
return certificatePinner;
}
@Override public boolean equals(@Nullable Object other) {
return other instanceof Address
&& url.equals(((Address) other).url)
&& equalsNonHost((Address) other);
}
@Override public int hashCode() {
int result = 17;
result = 31 * result + url.hashCode();
result = 31 * result + dns.hashCode();
result = 31 * result + proxyAuthenticator.hashCode();
result = 31 * result + protocols.hashCode();
result = 31 * result + connectionSpecs.hashCode();
result = 31 * result + proxySelector.hashCode();
result = 31 * result + (proxy != null ? proxy.hashCode() : 0);
result = 31 * result + (sslSocketFactory != null ? sslSocketFactory.hashCode() : 0);
result = 31 * result + (hostnameVerifier != null ? hostnameVerifier.hashCode() : 0);
result = 31 * result + (certificatePinner != null ? certificatePinner.hashCode() : 0);
return result;
}
boolean equalsNonHost(Address that) {
return this.dns.equals(that.dns)
&& this.proxyAuthenticator.equals(that.proxyAuthenticator)
&& this.protocols.equals(that.protocols)
&& this.connectionSpecs.equals(that.connectionSpecs)
&& this.proxySelector.equals(that.proxySelector)
&& equal(this.proxy, that.proxy)
&& equal(this.sslSocketFactory, that.sslSocketFactory)
&& equal(this.hostnameVerifier, that.hostnameVerifier)
&& equal(this.certificatePinner, that.certificatePinner)
&& this.url().port() == that.url().port();
}
@Override public String toString() {
StringBuilder result = new StringBuilder()
.append("Address{")
.append(url.host()).append(":").append(url.port());
if (proxy != null) {
result.append(", proxy=").append(proxy);
} else {
result.append(", proxySelector=").append(proxySelector);
}
result.append("}");
return result.toString();
}
}
/*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp4;
import java.io.IOException;
import androidx.annotation.Nullable;
/**
* Responds to an authentication challenge from either a remote web server or a proxy server.
* Implementations may either attempt to satisfy the challenge by returning a request that includes
* an authorization header, or they may refuse the challenge by returning null. In this case the
* unauthenticated response will be returned to the caller that triggered it.
*
* <p>Implementations should check if the initial request already included an attempt to
* authenticate. If so it is likely that further attempts will not be useful and the authenticator
* should give up.
*
* <p>When authentication is requested by an origin server, the response code is 401 and the
* implementation should respond with a new request that sets the "Authorization" header.
* <pre> {@code
*
* if (response.request().header("Authorization") != null) {
* return null; // Give up, we've already failed to authenticate.
* }
*
* String credential = Credentials.basic(...)
* return response.request().newBuilder()
* .header("Authorization", credential)
* .build();
* }</pre>
*
* <p>When authentication is requested by a proxy server, the response code is 407 and the
* implementation should respond with a new request that sets the "Proxy-Authorization" header.
* <pre> {@code
*
* if (response.request().header("Proxy-Authorization") != null) {
* return null; // Give up, we've already failed to authenticate.
* }
*
* String credential = Credentials.basic(...)
* return response.request().newBuilder()
* .header("Proxy-Authorization", credential)
* .build();
* }</pre>
*
* <p>Applications may configure OkHttp with an authenticator for origin servers, or proxy servers,
* or both.
*/
public interface Authenticator {
/** An authenticator that knows no credentials and makes no attempt to authenticate. */
Authenticator NONE = new Authenticator() {
@Override public Request authenticate(Route route, Response response) {
return null;
}
};
/**
* Returns a request that includes a credential to satisfy an authentication challenge in {@code
* response}. Returns null if the challenge cannot be satisfied.
*/
@Nullable Request authenticate(Route route, Response response) throws IOException;
}
This diff is collapsed.
This diff is collapsed.
/*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp4;
import java.io.IOException;
/**
* A call is a request that has been prepared for execution. A call can be canceled. As this object
* represents a single request/response pair (stream), it cannot be executed twice.
*/
public interface Call extends Cloneable {
/** Returns the original request that initiated this call. */
Request request();
/**
* Invokes the request immediately, and blocks until the response can be processed or is in
* error.
*
* <p>To avoid leaking resources callers should close the {@link Response} which in turn will
* close the underlying {@link ResponseBody}.
*
* <pre>@{code
*
* // ensure the response (and underlying response body) is closed
* try (Response response = client.newCall(request).execute()) {
* ...
* }
*
* }</pre>
*
* <p>The caller may read the response body with the response's {@link Response#body} method. To
* avoid leaking resources callers must {@linkplain ResponseBody close the response body} or the
* Response.
*
* <p>Note that transport-layer success (receiving a HTTP response code, headers and body) does
* not necessarily indicate application-layer success: {@code response} may still indicate an
* unhappy HTTP response code like 404 or 500.
*
* @throws IOException if the request could not be executed due to cancellation, a connectivity
* problem or timeout. Because networks can fail during an exchange, it is possible that the
* remote server accepted the request before the failure.
* @throws IllegalStateException when the call has already been executed.
*/
Response execute() throws IOException;
/**
* Schedules the request to be executed at some point in the future.
*
* <p>The {@link OkHttpClient#dispatcher dispatcher} defines when the request will run: usually
* immediately unless there are several other requests currently being executed.
*
* <p>This client will later call back {@code responseCallback} with either an HTTP response or a
* failure exception.
*
* @throws IllegalStateException when the call has already been executed.
*/
void enqueue(Callback responseCallback);
/** Cancels the request, if possible. Requests that are already complete cannot be canceled. */
void cancel();
/**
* Returns true if this call has been either {@linkplain #execute() executed} or {@linkplain
* #enqueue(Callback) enqueued}. It is an error to execute a call more than once.
*/
boolean isExecuted();
boolean isCanceled();
/**
* Create a new, identical call to this one which can be enqueued or executed even if this call
* has already been.
*/
Call clone();
interface Factory {
Call newCall(Request request);
}
}
/*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp4;
import java.io.IOException;
public interface Callback {
/**
* Called when the request could not be executed due to cancellation, a connectivity problem or
* timeout. Because networks can fail during an exchange, it is possible that the remote server
* accepted the request before the failure.
*/
void onFailure(Call call, IOException e);
/**
* Called when the HTTP response was successfully returned by the remote server. The callback may
* proceed to read the response body with {@link Response#body}. The response is still live until
* its response body is {@linkplain ResponseBody closed}. The recipient of the callback may
* consume the response body on another thread.
*
* <p>Note that transport-layer success (receiving a HTTP response code, headers and body) does
* not necessarily indicate application-layer success: {@code response} may still indicate an
* unhappy HTTP response code like 404 or 500.
*/
void onResponse(Call call, Response response) throws IOException;
}
This diff is collapsed.
/*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp4;
import static okhttp4.internal.Util.ISO_8859_1;
import java.nio.charset.Charset;
import androidx.annotation.Nullable;
/** An RFC 7617 challenge. */
public final class Challenge {
private final String scheme;
private final String realm;
private final Charset charset;
public Challenge(String scheme, String realm) {
this(scheme, realm, ISO_8859_1);
}
private Challenge(String scheme, String realm, Charset charset) {
if (scheme == null) throw new NullPointerException("scheme == null");
if (realm == null) throw new NullPointerException("realm == null");
if (charset == null) throw new NullPointerException("charset == null");
this.scheme = scheme;
this.realm = realm;
this.charset = charset;
}
/** Returns a copy of this charset that expects a credential encoded with {@code charset}. */
public Challenge withCharset(Charset charset) {
return new Challenge(scheme, realm, charset);
}
/** Returns the authentication scheme, like {@code Basic}. */
public String scheme() {
return scheme;
}
/** Returns the protection space. */
public String realm() {
return realm;
}
/** Returns the charset that should be used to encode the credential. */
public Charset charset() {
return charset;
}
@Override public boolean equals(@Nullable Object other) {
return other instanceof Challenge
&& ((Challenge) other).scheme.equals(scheme)
&& ((Challenge) other).realm.equals(realm)
&& ((Challenge) other).charset.equals(charset);
}
@Override public int hashCode() {
int result = 29;
result = 31 * result + realm.hashCode();
result = 31 * result + scheme.hashCode();
result = 31 * result + charset.hashCode();
return result;
}
@Override public String toString() {
return scheme
+ " realm=\"" + realm + "\""
+ " charset=\"" + charset + "\"";
}
}
This diff is collapsed.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp4;
import java.net.Socket;
import androidx.annotation.Nullable;
/**
* The sockets and streams of an HTTP, HTTPS, or HTTPS+HTTP/2 connection. May be used for multiple
* HTTP request/response exchanges. Connections may be direct to the origin server or via a proxy.
*
* <p>Typically instances of this class are created, connected and exercised automatically by the
* HTTP client. Applications may use this class to monitor HTTP connections as members of a
* {@linkplain ConnectionPool connection pool}.
*
* <p>Do not confuse this class with the misnamed {@code HttpURLConnection}, which isn't so much a
* connection as a single request/response exchange.
*
* <h3>Modern TLS</h3>
*
* <p>There are tradeoffs when selecting which options to include when negotiating a secure
* connection to a remote host. Newer TLS options are quite useful:
*
* <ul>
* <li>Server Name Indication (SNI) enables one IP address to negotiate secure connections for
* multiple domain names.
* <li>Application Layer Protocol Negotiation (ALPN) enables the HTTPS port (443) to be used to
* negotiate HTTP/2.
* </ul>
*
* <p>Unfortunately, older HTTPS servers refuse to connect when such options are presented. Rather
* than avoiding these options entirely, this class allows a connection to be attempted with modern
* options and then retried without them should the attempt fail.
*
* <h3>Connection Reuse</h3>
*
* <p>Each connection can carry a varying number of streams, depending on the underlying protocol
* being used. HTTP/1.x connections can carry either zero or one streams. HTTP/2 connections can
* carry any number of streams, dynamically configured with {@code SETTINGS_MAX_CONCURRENT_STREAMS}.
* A connection currently carrying zero streams is an idle stream. We keep it alive because reusing
* an existing connection is typically faster than establishing a new one.
*
* <p>When a single logical call requires multiple streams due to redirects or authorization
* challenges, we prefer to use the same physical connection for all streams in the sequence. There
* are potential performance and behavior consequences to this preference. To support this feature,
* this class separates <i>allocations</i> from <i>streams</i>. An allocation is created by a call,
* used for one or more streams, and then released. An allocated connection won't be stolen by other
* calls while a redirect or authorization challenge is being handled.
*
* <p>When the maximum concurrent streams limit is reduced, some allocations will be rescinded.
* Attempting to create new streams on these allocations will fail.
*
* <p>Note that an allocation may be released before its stream is completed. This is intended to
* make bookkeeping easier for the caller: releasing the allocation as soon as the terminal stream
* has been found. But only complete the stream once its data stream has been exhausted.
*/
public interface Connection {
/** Returns the route used by this connection. */
Route route();
/**
* Returns the socket that this connection is using. Returns an {@linkplain
* javax.net.ssl.SSLSocket SSL socket} if this connection is HTTPS. If this is an HTTP/2
* connection the socket may be shared by multiple concurrent calls.
*/
Socket socket();
/**
* Returns the TLS handshake used to establish this connection, or null if the connection is not
* HTTPS.
*/
@Nullable Handshake handshake();
/**
* Returns the protocol negotiated by this connection, or {@link Protocol#HTTP_1_1} if no protocol
* has been negotiated. This method returns {@link Protocol#HTTP_1_1} even if the remote peer is
* using {@link Protocol#HTTP_1_0}.
*/
Protocol protocol();
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
/*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp4;
import java.util.Collections;
import java.util.List;
/**
* Provides <strong>policy</strong> and <strong>persistence</strong> for HTTP cookies.
*
* <p>As policy, implementations of this interface are responsible for selecting which cookies to
* accept and which to reject. A reasonable policy is to reject all cookies, though that may
* interfere with session-based authentication schemes that require cookies.
*
* <p>As persistence, implementations of this interface must also provide storage of cookies. Simple
* implementations may store cookies in memory; sophisticated ones may use the file system or
* database to hold accepted cookies. The <a
* href="https://tools.ietf.org/html/rfc6265#section-5.3">cookie storage model</a> specifies
* policies for updating and expiring cookies.
*/
public interface CookieJar {
/** A cookie jar that never accepts any cookies. */
CookieJar NO_COOKIES = new CookieJar() {
@Override public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
}
@Override public List<Cookie> loadForRequest(HttpUrl url) {
return Collections.emptyList();
}
};
/**
* Saves {@code cookies} from an HTTP response to this store according to this jar's policy.
*
* <p>Note that this method may be called a second time for a single HTTP response if the response
* includes a trailer. For this obscure HTTP feature, {@code cookies} contains only the trailer's
* cookies.
*/
void saveFromResponse(HttpUrl url, List<Cookie> cookies);
/**
* Load cookies from the jar for an HTTP request to {@code url}. This method returns a possibly
* empty list of cookies for the network request.
*
* <p>Simple implementations will return the accepted cookies that have not yet expired and that
* {@linkplain Cookie#matches match} {@code url}.
*/
List<Cookie> loadForRequest(HttpUrl url);
}
/*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp4;
import static okhttp4.internal.Util.ISO_8859_1;
import java.nio.charset.Charset;
import okio.ByteString;
/** Factory for HTTP authorization credentials. */
public final class Credentials {
private Credentials() {
}
/** Returns an auth credential for the Basic scheme. */
public static String basic(String userName, String password) {
return basic(userName, password, ISO_8859_1);
}
public static String basic(String userName, String password, Charset charset) {
String usernameAndPassword = userName + ":" + password;
String encoded = ByteString.encodeString(usernameAndPassword, charset).base64();
return "Basic " + encoded;
}
}
/*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp4;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import androidx.annotation.Nullable;
import okhttp4.RealCall.AsyncCall;
import okhttp4.internal.Util;
/**
* Policy on when async requests are executed.
*
* <p>Each dispatcher uses an {@link ExecutorService} to run calls internally. If you supply your
* own executor, it should be able to run {@linkplain #getMaxRequests the configured maximum} number
* of calls concurrently.
*/
public final class Dispatcher {
private int maxRequests = 64;
private int maxRequestsPerHost = 5;
private @Nullable Runnable idleCallback;
/** Executes calls. Created lazily. */
private @Nullable ExecutorService executorService;
/** Ready async calls in the order they'll be run. */
private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>();
/** Running asynchronous calls. Includes canceled calls that haven't finished yet. */
private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();
/** Running synchronous calls. Includes canceled calls that haven't finished yet. */
private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>();
public Dispatcher(ExecutorService executorService) {
this.executorService = executorService;
}
public Dispatcher() {
}
public synchronized ExecutorService executorService() {
if (executorService == null) {
executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false));
}
return executorService;
}
/**
* Set the maximum number of requests to execute concurrently. Above this requests queue in
* memory, waiting for the running calls to complete.
*
* <p>If more than {@code maxRequests} requests are in flight when this is invoked, those requests
* will remain in flight.
*/
public synchronized void setMaxRequests(int maxRequests) {
if (maxRequests < 1) {
throw new IllegalArgumentException("max < 1: " + maxRequests);
}
this.maxRequests = maxRequests;
promoteCalls();
}
public synchronized int getMaxRequests() {
return maxRequests;
}
/**
* Set the maximum number of requests for each host to execute concurrently. This limits requests
* by the URL's host name. Note that concurrent requests to a single IP address may still exceed
* this limit: multiple hostnames may share an IP address or be routed through the same HTTP
* proxy.
*
* <p>If more than {@code maxRequestsPerHost} requests are in flight when this is invoked, those
* requests will remain in flight.
*/
public synchronized void setMaxRequestsPerHost(int maxRequestsPerHost) {
if (maxRequestsPerHost < 1) {
throw new IllegalArgumentException("max < 1: " + maxRequestsPerHost);
}
this.maxRequestsPerHost = maxRequestsPerHost;
promoteCalls();
}
public synchronized int getMaxRequestsPerHost() {
return maxRequestsPerHost;
}
/**
* Set a callback to be invoked each time the dispatcher becomes idle (when the number of running
* calls returns to zero).
*
* <p>Note: The time at which a {@linkplain Call call} is considered idle is different depending
* on whether it was run {@linkplain Call#enqueue(Callback) asynchronously} or
* {@linkplain Call#execute() synchronously}. Asynchronous calls become idle after the
* {@link Callback#onResponse onResponse} or {@link Callback#onFailure onFailure} callback has
* returned. Synchronous calls become idle once {@link Call#execute() execute()} returns. This
* means that if you are doing synchronous calls the network layer will not truly be idle until
* every returned {@link Response} has been closed.
*/
public synchronized void setIdleCallback(@Nullable Runnable idleCallback) {
this.idleCallback = idleCallback;
}
synchronized void enqueue(AsyncCall call) {
if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
runningAsyncCalls.add(call);
executorService().execute(call);
} else {
readyAsyncCalls.add(call);
}
}
/**
* Cancel all calls currently enqueued or executing. Includes calls executed both {@linkplain
* Call#execute() synchronously} and {@linkplain Call#enqueue asynchronously}.
*/
public synchronized void cancelAll() {
for (AsyncCall call : readyAsyncCalls) {
call.get().cancel();
}
for (AsyncCall call : runningAsyncCalls) {
call.get().cancel();
}
for (RealCall call : runningSyncCalls) {
call.cancel();
}
}
private void promoteCalls() {
if (runningAsyncCalls.size() >= maxRequests) return; // Already running max capacity.
if (readyAsyncCalls.isEmpty()) return; // No ready calls to promote.
for (Iterator<AsyncCall> i = readyAsyncCalls.iterator(); i.hasNext(); ) {
AsyncCall call = i.next();
if (runningCallsForHost(call) < maxRequestsPerHost) {
i.remove();
runningAsyncCalls.add(call);
executorService().execute(call);
}
if (runningAsyncCalls.size() >= maxRequests) return; // Reached max capacity.
}
}
/** Returns the number of running calls that share a host with {@code call}. */
private int runningCallsForHost(AsyncCall call) {
int result = 0;
for (AsyncCall c : runningAsyncCalls) {
if (c.host().equals(call.host())) result++;
}
return result;
}
/** Used by {@code Call#execute} to signal it is in-flight. */
synchronized void executed(RealCall call) {
runningSyncCalls.add(call);
}
/** Used by {@code AsyncCall#run} to signal completion. */
void finished(AsyncCall call) {
finished(runningAsyncCalls, call, true);
}
/** Used by {@code Call#execute} to signal completion. */
void finished(RealCall call) {
finished(runningSyncCalls, call, false);
}
private <T> void finished(Deque<T> calls, T call, boolean promoteCalls) {
int runningCallsCount;
Runnable idleCallback;
synchronized (this) {
if (!calls.remove(call)) throw new AssertionError("Call wasn't in-flight!");
if (promoteCalls) promoteCalls();
runningCallsCount = runningCallsCount();
idleCallback = this.idleCallback;
}
if (runningCallsCount == 0 && idleCallback != null) {
idleCallback.run();
}
}
/** Returns a snapshot of the calls currently awaiting execution. */
public synchronized List<Call> queuedCalls() {
List<Call> result = new ArrayList<>();
for (AsyncCall asyncCall : readyAsyncCalls) {
result.add(asyncCall.get());
}
return Collections.unmodifiableList(result);
}
/** Returns a snapshot of the calls currently being executed. */
public synchronized List<Call> runningCalls() {
List<Call> result = new ArrayList<>();
result.addAll(runningSyncCalls);
for (AsyncCall asyncCall : runningAsyncCalls) {
result.add(asyncCall.get());
}
return Collections.unmodifiableList(result);
}
public synchronized int queuedCallsCount() {
return readyAsyncCalls.size();
}
public synchronized int runningCallsCount() {
return runningAsyncCalls.size() + runningSyncCalls.size();
}
}
/*
* Copyright (C) 2012 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp4;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
/**
* A domain name service that resolves IP addresses for host names. Most applications will use the
* {@linkplain #SYSTEM system DNS service}, which is the default. Some applications may provide
* their own implementation to use a different DNS server, to prefer IPv6 addresses, to prefer IPv4
* addresses, or to force a specific known IP address.
*
* <p>Implementations of this interface must be safe for concurrent use.
*/
public interface Dns {
/**
* A DNS that uses {@link InetAddress#getAllByName} to ask the underlying operating system to
* lookup IP addresses. Most custom {@link Dns} implementations should delegate to this instance.
*/
Dns SYSTEM = new Dns() {
@Override public List<InetAddress> lookup(String hostname) throws UnknownHostException {
if (hostname == null) throw new UnknownHostException("hostname == null");
return Arrays.asList(InetAddress.getAllByName(hostname));
}
};
/**
* Returns the IP addresses of {@code hostname}, in the order they will be attempted by OkHttp. If
* a connection to an address fails, OkHttp will retry the connection with the next address until
* either a connection is made, the set of IP addresses is exhausted, or a limit is exceeded.
*/
List<InetAddress> lookup(String hostname) throws UnknownHostException;
}
This diff is collapsed.
/*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp4;
import static okhttp4.HttpUrl.FORM_ENCODE_SET;
import static okhttp4.HttpUrl.percentDecode;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.Nullable;
import okhttp4.internal.Util;
import okio.Buffer;
import okio.BufferedSink;
public final class FormBody extends RequestBody {
private static final MediaType CONTENT_TYPE =
MediaType.parse("application/x-www-form-urlencoded");
private final List<String> encodedNames;
private final List<String> encodedValues;
FormBody(List<String> encodedNames, List<String> encodedValues) {
this.encodedNames = Util.immutableList(encodedNames);
this.encodedValues = Util.immutableList(encodedValues);
}
/** The number of key-value pairs in this form-encoded body. */
public int size() {
return encodedNames.size();
}
public String encodedName(int index) {
return encodedNames.get(index);
}
public String name(int index) {
return percentDecode(encodedName(index), true);
}
public String encodedValue(int index) {
return encodedValues.get(index);
}
public String value(int index) {
return percentDecode(encodedValue(index), true);
}
@Override public MediaType contentType() {
return CONTENT_TYPE;
}
@Override public long contentLength() {
return writeOrCountBytes(null, true);
}
@Override public void writeTo(BufferedSink sink) throws IOException {
writeOrCountBytes(sink, false);
}
/**
* Either writes this request to {@code sink} or measures its content length. We have one method
* do double-duty to make sure the counting and content are consistent, particularly when it comes
* to awkward operations like measuring the encoded length of header strings, or the
* length-in-digits of an encoded integer.
*/
private long writeOrCountBytes(@Nullable BufferedSink sink, boolean countBytes) {
long byteCount = 0L;
Buffer buffer;
if (countBytes) {
buffer = new Buffer();
} else {
buffer = sink.buffer();
}
for (int i = 0, size = encodedNames.size(); i < size; i++) {
if (i > 0) buffer.writeByte('&');
buffer.writeUtf8(encodedNames.get(i));
buffer.writeByte('=');
buffer.writeUtf8(encodedValues.get(i));
}
if (countBytes) {
byteCount = buffer.size();
buffer.clear();
}
return byteCount;
}
public static final class Builder {
private final List<String> names = new ArrayList<>();
private final List<String> values = new ArrayList<>();
private final Charset charset;
public Builder() {
this(null);
}
public Builder(Charset charset) {
this.charset = charset;
}
public Builder add(String name, String value) {
names.add(HttpUrl.canonicalize(name, FORM_ENCODE_SET, false, false, true, true, charset));
values.add(HttpUrl.canonicalize(value, FORM_ENCODE_SET, false, false, true, true, charset));
return this;
}
public Builder addEncoded(String name, String value) {
names.add(HttpUrl.canonicalize(name, FORM_ENCODE_SET, true, false, true, true, charset));
values.add(HttpUrl.canonicalize(value, FORM_ENCODE_SET, true, false, true, true, charset));
return this;
}
public FormBody build() {
return new FormBody(names, values);
}
}
}
/*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp4;
import java.security.Principal;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.List;
import androidx.annotation.Nullable;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import okhttp4.internal.Util;
/**
* A record of a TLS handshake. For HTTPS clients, the client is <i>local</i> and the remote server
* is its <i>peer</i>.
*
* <p>This value object describes a completed handshake. Use {@link ConnectionSpec} to set policy
* for new handshakes.
*/
public final class Handshake {
private final TlsVersion tlsVersion;
private final CipherSuite cipherSuite;
private final List<Certificate> peerCertificates;
private final List<Certificate> localCertificates;
private Handshake(TlsVersion tlsVersion, CipherSuite cipherSuite,
List<Certificate> peerCertificates, List<Certificate> localCertificates) {
this.tlsVersion = tlsVersion;
this.cipherSuite = cipherSuite;
this.peerCertificates = peerCertificates;
this.localCertificates = localCertificates;
}
public static Handshake get(SSLSession session) {
String cipherSuiteString = session.getCipherSuite();
if (cipherSuiteString == null) throw new IllegalStateException("cipherSuite == null");
CipherSuite cipherSuite = CipherSuite.forJavaName(cipherSuiteString);
String tlsVersionString = session.getProtocol();
if (tlsVersionString == null) throw new IllegalStateException("tlsVersion == null");
TlsVersion tlsVersion = TlsVersion.forJavaName(tlsVersionString);
Certificate[] peerCertificates;
try {
peerCertificates = session.getPeerCertificates();
} catch (SSLPeerUnverifiedException ignored) {
peerCertificates = null;
}
List<Certificate> peerCertificatesList = peerCertificates != null
? Util.immutableList(peerCertificates)
: Collections.<Certificate>emptyList();
Certificate[] localCertificates = session.getLocalCertificates();
List<Certificate> localCertificatesList = localCertificates != null
? Util.immutableList(localCertificates)
: Collections.<Certificate>emptyList();
return new Handshake(tlsVersion, cipherSuite, peerCertificatesList, localCertificatesList);
}
public static Handshake get(TlsVersion tlsVersion, CipherSuite cipherSuite,
List<Certificate> peerCertificates, List<Certificate> localCertificates) {
if (tlsVersion == null) throw new NullPointerException("tlsVersion == null");
if (cipherSuite == null) throw new NullPointerException("cipherSuite == null");
return new Handshake(tlsVersion, cipherSuite, Util.immutableList(peerCertificates),
Util.immutableList(localCertificates));
}
/**
* Returns the TLS version used for this connection. This value wasn't tracked prior to OkHttp
* 3.0. For responses cached by preceding versions this returns {@link TlsVersion#SSL_3_0}.
*/
public TlsVersion tlsVersion() {
return tlsVersion;
}
/** Returns the cipher suite used for the connection. */
public CipherSuite cipherSuite() {
return cipherSuite;
}
/** Returns a possibly-empty list of certificates that identify the remote peer. */
public List<Certificate> peerCertificates() {
return peerCertificates;
}
/** Returns the remote peer's principle, or null if that peer is anonymous. */
public @Nullable Principal peerPrincipal() {
return !peerCertificates.isEmpty()
? ((X509Certificate) peerCertificates.get(0)).getSubjectX500Principal()
: null;
}
/** Returns a possibly-empty list of certificates that identify this peer. */
public List<Certificate> localCertificates() {
return localCertificates;
}
/** Returns the local principle, or null if this peer is anonymous. */
public @Nullable Principal localPrincipal() {
return !localCertificates.isEmpty()
? ((X509Certificate) localCertificates.get(0)).getSubjectX500Principal()
: null;
}
@Override public boolean equals(@Nullable Object other) {
if (!(other instanceof Handshake)) return false;
Handshake that = (Handshake) other;
return tlsVersion.equals(that.tlsVersion)
&& cipherSuite.equals(that.cipherSuite)
&& peerCertificates.equals(that.peerCertificates)
&& localCertificates.equals(that.localCertificates);
}
@Override public int hashCode() {
int result = 17;
result = 31 * result + tlsVersion.hashCode();
result = 31 * result + cipherSuite.hashCode();
result = 31 * result + peerCertificates.hashCode();
result = 31 * result + localCertificates.hashCode();
return result;
}
}
This diff is collapsed.
This diff is collapsed.
/*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp4;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import androidx.annotation.Nullable;
/**
* Observes, modifies, and potentially short-circuits requests going out and the corresponding
* responses coming back in. Typically interceptors add, remove, or transform headers on the request
* or response.
*/
public interface Interceptor {
Response intercept(Chain chain) throws IOException;
interface Chain {
Request request();
Response proceed(Request request) throws IOException;
/**
* Returns the connection the request will be executed on. This is only available in the chains
* of network interceptors; for application interceptors this is always null.
*/
@Nullable Connection connection();
Call call();
int connectTimeoutMillis();
Chain withConnectTimeout(int timeout, TimeUnit unit);
int readTimeoutMillis();
Chain withReadTimeout(int timeout, TimeUnit unit);
int writeTimeoutMillis();
Chain withWriteTimeout(int timeout, TimeUnit unit);
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
/*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp4.internal.cache;
import java.io.IOException;
import okio.Sink;
public interface CacheRequest {
Sink body() throws IOException;
void abort();
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment