okhttp3.internal.Util Java Examples

The following examples show how to use okhttp3.internal.Util. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConnectionSpec.java    From styT with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a copy of this that omits cipher suites and TLS versions not enabled by {@code
 * sslSocket}.
 */
private ConnectionSpec supportedSpec(SSLSocket sslSocket, boolean isFallback) {
  String[] cipherSuitesIntersection = cipherSuites != null
      ? intersect(CipherSuite.ORDER_BY_NAME, sslSocket.getEnabledCipherSuites(), cipherSuites)
      : sslSocket.getEnabledCipherSuites();
  String[] tlsVersionsIntersection = tlsVersions != null
      ? intersect(Util.NATURAL_ORDER, sslSocket.getEnabledProtocols(), tlsVersions)
      : sslSocket.getEnabledProtocols();

  // In accordance with https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-00
  // the SCSV cipher is added to signal that a protocol fallback has taken place.
  String[] supportedCipherSuites = sslSocket.getSupportedCipherSuites();
  int indexOfFallbackScsv = indexOf(
      CipherSuite.ORDER_BY_NAME, supportedCipherSuites, "TLS_FALLBACK_SCSV");
  if (isFallback && indexOfFallbackScsv != -1) {
    cipherSuitesIntersection = concat(
        cipherSuitesIntersection, supportedCipherSuites[indexOfFallbackScsv]);
  }

  return new Builder(this)
      .cipherSuites(cipherSuitesIntersection)
      .tlsVersions(tlsVersionsIntersection)
      .build();
}
 
Example #2
Source File: RealWebSocket.java    From styT with Apache License 2.0 6 votes vote down vote up
public void initReaderAndWriter(
    String name, long pingIntervalMillis, Streams streams) throws IOException {
  synchronized (this) {
    this.streams = streams;
    this.writer = new WebSocketWriter(streams.client, streams.sink, random);
    this.executor = new ScheduledThreadPoolExecutor(1, Util.threadFactory(name, false));
    if (pingIntervalMillis != 0) {
      executor.scheduleAtFixedRate(
          new PingRunnable(), pingIntervalMillis, pingIntervalMillis, MILLISECONDS);
    }
    if (!messageAndCloseQueue.isEmpty()) {
      runWriter(); // Send messages that were enqueued before we were connected.
    }
  }

  reader = new WebSocketReader(streams.client, streams.source, this);
}
 
Example #3
Source File: Http2Connection.java    From styT with Apache License 2.0 6 votes vote down vote up
/**
 * Degrades this connection such that new streams can neither be created locally, nor accepted
 * from the remote peer. Existing streams are not impacted. This is intended to permit an endpoint
 * to gracefully stop accepting new requests without harming previously established streams.
 */
public void shutdown(ErrorCode statusCode) throws IOException {
  synchronized (writer) {
    int lastGoodStreamId;
    synchronized (this) {
      if (shutdown) {
        return;
      }
      shutdown = true;
      lastGoodStreamId = this.lastGoodStreamId;
    }
    // TODO: propagate exception message into debugData.
    // TODO: configure a timeout on the reader so that it doesn’t block forever.
    writer.goAway(lastGoodStreamId, statusCode, Util.EMPTY_BYTE_ARRAY);
  }
}
 
Example #4
Source File: Http2Connection.java    From styT with Apache License 2.0 6 votes vote down vote up
@Override protected void execute() {
  ErrorCode connectionErrorCode = ErrorCode.INTERNAL_ERROR;
  ErrorCode streamErrorCode = ErrorCode.INTERNAL_ERROR;
  try {
    reader.readConnectionPreface(this);
    while (reader.nextFrame(false, this)) {
    }
    connectionErrorCode = ErrorCode.NO_ERROR;
    streamErrorCode = ErrorCode.CANCEL;
  } catch (IOException e) {
    connectionErrorCode = ErrorCode.PROTOCOL_ERROR;
    streamErrorCode = ErrorCode.PROTOCOL_ERROR;
  } finally {
    try {
      close(connectionErrorCode, streamErrorCode);
    } catch (IOException ignored) {
    }
    Util.closeQuietly(reader);
  }
}
 
Example #5
Source File: RequestBody.java    From AndroidProjects with MIT License 6 votes vote down vote up
/** Returns a new request body that transmits {@code content}. */
public static RequestBody create(final MediaType contentType, final byte[] content,
    final int offset, final int byteCount) {
  if (content == null) throw new NullPointerException("content == null");
  Util.checkOffsetAndCount(content.length, offset, byteCount);
  return new RequestBody() {
    @Override public MediaType contentType() {
      return contentType;
    }

    @Override public long contentLength() {
      return byteCount;
    }

    @Override public void writeTo(BufferedSink sink) throws IOException {
      sink.write(content, offset, byteCount);
    }
  };
}
 
Example #6
Source File: DiskLruCache.java    From AndroidProjects with MIT License 6 votes vote down vote up
/**
 * Create a cache which will reside in {@code directory}. This cache is lazily initialized on
 * first access and will be created if it does not exist.
 *
 * @param directory a writable directory
 * @param valueCount the number of values per cache entry. Must be positive.
 * @param maxSize the maximum number of bytes this cache should use to store
 */
public static DiskLruCache create(FileSystem fileSystem, File directory, int appVersion,
    int valueCount, long maxSize) {
  if (maxSize <= 0) {
    throw new IllegalArgumentException("maxSize <= 0");
  }
  if (valueCount <= 0) {
    throw new IllegalArgumentException("valueCount <= 0");
  }

  // Use a single background thread to evict entries.
  Executor executor = new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS,
      new LinkedBlockingQueue<Runnable>(), Util.threadFactory("OkHttp DiskLruCache", true));

  return new DiskLruCache(fileSystem, directory, appVersion, valueCount, maxSize, executor);
}
 
Example #7
Source File: RequestBody.java    From styT with Apache License 2.0 6 votes vote down vote up
/** Returns a new request body that transmits {@code content}. */
public static RequestBody create(final MediaType contentType, final byte[] content,
    final int offset, final int byteCount) {
  if (content == null) throw new NullPointerException("content == null");
  Util.checkOffsetAndCount(content.length, offset, byteCount);
  return new RequestBody() {
    @Override public MediaType contentType() {
      return contentType;
    }

    @Override public long contentLength() {
      return byteCount;
    }

    @Override public void writeTo(BufferedSink sink) throws IOException {
      sink.write(content, offset, byteCount);
    }
  };
}
 
Example #8
Source File: ConnectionSpec.java    From AndroidProjects with MIT License 6 votes vote down vote up
/**
 * Returns a copy of this that omits cipher suites and TLS versions not enabled by {@code
 * sslSocket}.
 */
private ConnectionSpec supportedSpec(SSLSocket sslSocket, boolean isFallback) {
  String[] cipherSuitesIntersection = cipherSuites != null
      ? intersect(CipherSuite.ORDER_BY_NAME, sslSocket.getEnabledCipherSuites(), cipherSuites)
      : sslSocket.getEnabledCipherSuites();
  String[] tlsVersionsIntersection = tlsVersions != null
      ? intersect(Util.NATURAL_ORDER, sslSocket.getEnabledProtocols(), tlsVersions)
      : sslSocket.getEnabledProtocols();

  // In accordance with https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-00
  // the SCSV cipher is added to signal that a protocol fallback has taken place.
  String[] supportedCipherSuites = sslSocket.getSupportedCipherSuites();
  int indexOfFallbackScsv = indexOf(
      CipherSuite.ORDER_BY_NAME, supportedCipherSuites, "TLS_FALLBACK_SCSV");
  if (isFallback && indexOfFallbackScsv != -1) {
    cipherSuitesIntersection = concat(
        cipherSuitesIntersection, supportedCipherSuites[indexOfFallbackScsv]);
  }

  return new Builder(this)
      .cipherSuites(cipherSuitesIntersection)
      .tlsVersions(tlsVersionsIntersection)
      .build();
}
 
Example #9
Source File: DiskLruCache.java    From styT with Apache License 2.0 6 votes vote down vote up
/**
 * Create a cache which will reside in {@code directory}. This cache is lazily initialized on
 * first access and will be created if it does not exist.
 *
 * @param directory a writable directory
 * @param valueCount the number of values per cache entry. Must be positive.
 * @param maxSize the maximum number of bytes this cache should use to store
 */
public static DiskLruCache create(FileSystem fileSystem, File directory, int appVersion,
    int valueCount, long maxSize) {
  if (maxSize <= 0) {
    throw new IllegalArgumentException("maxSize <= 0");
  }
  if (valueCount <= 0) {
    throw new IllegalArgumentException("valueCount <= 0");
  }

  // Use a single background thread to evict entries.
  Executor executor = new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS,
      new LinkedBlockingQueue<Runnable>(), Util.threadFactory("OkHttp DiskLruCache", true));

  return new DiskLruCache(fileSystem, directory, appVersion, valueCount, maxSize, executor);
}
 
Example #10
Source File: FileProgressRequestBody.java    From tysq-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void writeTo(BufferedSink sink) throws IOException {
    Source source = null;
    try {
        source = Okio.source(file);
        long total = 0;
        long read;

        while ((read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) {
            total += read;
            sink.flush();
            this.listener.onTransferred(total);

        }
    } finally {
        Util.closeQuietly(source);
    }
}
 
Example #11
Source File: CountingFileRequestBody.java    From 4pdaClient-plus with Apache License 2.0 6 votes vote down vote up
@Override
public void writeTo(@NotNull BufferedSink sink) throws IOException {
    Source source = null;
    try {
        source = Okio.source(file);
        long total = 0;
        long read;

        while ((read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) {
            total += read;
            sink.flush();
            this.listener.transferred(total);

        }
    } finally {
        if (source != null)
            Util.closeQuietly(source);
    }
}
 
Example #12
Source File: Http2Connection.java    From AndroidProjects with MIT License 6 votes vote down vote up
@Override protected void execute() {
  ErrorCode connectionErrorCode = ErrorCode.INTERNAL_ERROR;
  ErrorCode streamErrorCode = ErrorCode.INTERNAL_ERROR;
  try {
    reader.readConnectionPreface(this);
    while (reader.nextFrame(false, this)) {
    }
    connectionErrorCode = ErrorCode.NO_ERROR;
    streamErrorCode = ErrorCode.CANCEL;
  } catch (IOException e) {
    connectionErrorCode = ErrorCode.PROTOCOL_ERROR;
    streamErrorCode = ErrorCode.PROTOCOL_ERROR;
  } finally {
    try {
      close(connectionErrorCode, streamErrorCode);
    } catch (IOException ignored) {
    }
    Util.closeQuietly(reader);
  }
}
 
Example #13
Source File: YandexDisk.java    From ariADDna with Apache License 2.0 5 votes vote down vote up
@Override
public JsonObject uploadExternalFile(File path, URL url) {
    HttpUrl uploadPath = ULOAD_PATH.newBuilder()
            .addQueryParameter("path", APP_ROOT + path.getPath())
            .addQueryParameter("url", url.toString())
            .build();

    request = postRequest(uploadPath, Util.EMPTY_REQUEST, tempAccessToken);
    result = sendRequest(client, request);

    return result;
}
 
Example #14
Source File: Address.java    From AndroidProjects with MIT License 5 votes vote down vote up
public Address(String uriHost, int uriPort, Dns dns, SocketFactory socketFactory,
    SSLSocketFactory sslSocketFactory, HostnameVerifier hostnameVerifier,
    CertificatePinner certificatePinner, Authenticator proxyAuthenticator, 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;
}
 
Example #15
Source File: DiskLruCache.java    From AndroidProjects with MIT License 5 votes vote down vote up
/**
 * Returns a snapshot of this entry. This opens all streams eagerly to guarantee that we see a
 * single published snapshot. If we opened streams lazily then the streams could come from
 * different edits.
 */
Snapshot snapshot() {
  if (!Thread.holdsLock(DiskLruCache.this)) throw new AssertionError();

  Source[] sources = new Source[valueCount];
  long[] lengths = this.lengths.clone(); // Defensive copy since these can be zeroed out.
  try {
    for (int i = 0; i < valueCount; i++) {
      sources[i] = fileSystem.source(cleanFiles[i]);
    }
    return new Snapshot(key, sequenceNumber, sources, lengths);
  } catch (FileNotFoundException e) {
    // A file must have been deleted manually!
    for (int i = 0; i < valueCount; i++) {
      if (sources[i] != null) {
        Util.closeQuietly(sources[i]);
      } else {
        break;
      }
    }
    // Since the entry is no longer valid, remove it so the metadata is accurate (i.e. the cache
    // size.)
    try {
      removeEntry(this);
    } catch (IOException ignored) {
    }
    return null;
  }
}
 
Example #16
Source File: ResponseBody.java    From AndroidProjects with MIT License 5 votes vote down vote up
@Override public int read(char[] cbuf, int off, int len) throws IOException {
  if (closed) throw new IOException("Stream closed");

  Reader delegate = this.delegate;
  if (delegate == null) {
    Charset charset = Util.bomAwareCharset(source, this.charset);
    delegate = this.delegate = new InputStreamReader(source.inputStream(), charset);
  }
  return delegate.read(cbuf, off, len);
}
 
Example #17
Source File: Http1Codec.java    From AndroidProjects with MIT License 5 votes vote down vote up
@Override public void close() throws IOException {
  if (closed) return;

  if (bytesRemaining != 0 && !Util.discard(this, DISCARD_STREAM_TIMEOUT_MILLIS, MILLISECONDS)) {
    endOfInput(false);
  }

  closed = true;
}
 
Example #18
Source File: Http1Codec.java    From AndroidProjects with MIT License 5 votes vote down vote up
@Override public void close() throws IOException {
  if (closed) return;
  if (hasMoreChunks && !Util.discard(this, DISCARD_STREAM_TIMEOUT_MILLIS, MILLISECONDS)) {
    endOfInput(false);
  }
  closed = true;
}
 
Example #19
Source File: JdkWithJettyBootPlatform.java    From AndroidProjects with MIT License 5 votes vote down vote up
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  String methodName = method.getName();
  Class<?> returnType = method.getReturnType();
  if (args == null) {
    args = Util.EMPTY_STRING_ARRAY;
  }
  if (methodName.equals("supports") && boolean.class == returnType) {
    return true; // ALPN is supported.
  } else if (methodName.equals("unsupported") && void.class == returnType) {
    this.unsupported = true; // Peer doesn't support ALPN.
    return null;
  } else if (methodName.equals("protocols") && args.length == 0) {
    return protocols; // Client advertises these protocols.
  } else if ((methodName.equals("selectProtocol") || methodName.equals("select"))
      && String.class == returnType && args.length == 1 && args[0] instanceof List) {
    List<String> peerProtocols = (List) args[0];
    // Pick the first known protocol the peer advertises.
    for (int i = 0, size = peerProtocols.size(); i < size; i++) {
      if (protocols.contains(peerProtocols.get(i))) {
        return selected = peerProtocols.get(i);
      }
    }
    return selected = protocols.get(0); // On no intersection, try peer's first protocol.
  } else if ((methodName.equals("protocolSelected") || methodName.equals("selected"))
      && args.length == 1) {
    this.selected = (String) args[0]; // Server selected this protocol.
    return null;
  } else {
    return method.invoke(this, args);
  }
}
 
Example #20
Source File: Http2Connection.java    From AndroidProjects with MIT License 5 votes vote down vote up
Http2Connection(Builder builder) {
  pushObserver = builder.pushObserver;
  client = builder.client;
  listener = builder.listener;
  // http://tools.ietf.org/html/draft-ietf-httpbis-http2-17#section-5.1.1
  nextStreamId = builder.client ? 1 : 2;
  if (builder.client) {
    nextStreamId += 2; // In HTTP/2, 1 on client is reserved for Upgrade.
  }

  nextPingId = builder.client ? 1 : 2;

  // Flow control was designed more for servers, or proxies than edge clients.
  // If we are a client, set the flow control window to 16MiB.  This avoids
  // thrashing window updates every 64KiB, yet small enough to avoid blowing
  // up the heap.
  if (builder.client) {
    okHttpSettings.set(Settings.INITIAL_WINDOW_SIZE, OKHTTP_CLIENT_WINDOW_SIZE);
  }

  hostname = builder.hostname;

  // Like newSingleThreadExecutor, except lazy creates the thread.
  pushExecutor = new ThreadPoolExecutor(0, 1, 60, TimeUnit.SECONDS,
      new LinkedBlockingQueue<Runnable>(),
      Util.threadFactory(Util.format("OkHttp %s Push Observer", hostname), true));
  peerSettings.set(Settings.INITIAL_WINDOW_SIZE, DEFAULT_INITIAL_WINDOW_SIZE);
  peerSettings.set(Settings.MAX_FRAME_SIZE, Http2.INITIAL_MAX_FRAME_SIZE);
  bytesLeftInWriteWindow = peerSettings.getInitialWindowSize();
  socket = builder.socket;
  writer = new Http2Writer(builder.sink, client);

  readerRunnable = new ReaderRunnable(new Http2Reader(builder.source, client));
}
 
Example #21
Source File: Handshake.java    From AndroidProjects with MIT License 5 votes vote down vote up
@Override public boolean equals(Object other) {
  if (!(other instanceof Handshake)) return false;
  Handshake that = (Handshake) other;
  return Util.equal(cipherSuite, that.cipherSuite)
      && cipherSuite.equals(that.cipherSuite)
      && peerCertificates.equals(that.peerCertificates)
      && localCertificates.equals(that.localCertificates);
}
 
Example #22
Source File: RequestTest.java    From HttPizza with Apache License 2.0 5 votes vote down vote up
@Test
public void string() throws Exception {
    MediaType contentType = MediaType.parse("text/plain; charset=utf-8");
    RequestBody body = RequestBody.create(contentType, "abc".getBytes(Util.UTF_8));
    assertEquals(contentType, body.contentType());
    assertEquals(3, body.contentLength());
    assertEquals("616263", bodyToHex(body));
    assertEquals("Retransmit body", "616263", bodyToHex(body));
}
 
Example #23
Source File: XOAuthProvider.java    From RxUploader with Apache License 2.0 5 votes vote down vote up
@Override
protected HttpRequest createRequest(String endpointUrl) throws Exception {
    final Request.Builder builder =
            new Request.Builder()
                    .url(endpointUrl)
                    .post(Util.EMPTY_REQUEST);
    if (endpointUrl.contains(Config.ACCESS_TOKEN_URL)) {
        final MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        final String body =
                String.format("x_auth_mode=%s&x_auth_password=%s&x_auth_username=%s",
                        Config.X_AUTH_MODE, Config.X_AUTH_PASSWORD, Config.X_AUTH_USERNAME);
        builder.post(RequestBody.create(mediaType, body));
    }
    return new OkHttpRequestAdapter(builder.build());
}
 
Example #24
Source File: GlobalConfigModule.java    From MVPArms with Apache License 2.0 5 votes vote down vote up
/**
 * 返回一个全局公用的线程池,适用于大多数异步需求。
 * 避免多个线程池创建带来的资源消耗。
 *
 * @return {@link Executor}
 */
@Singleton
@Provides
ExecutorService provideExecutorService() {
    return mExecutorService == null ? new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
            new SynchronousQueue<>(), Util.threadFactory("Arms Executor", false)) : mExecutorService;
}
 
Example #25
Source File: DiskLruCache.java    From AndroidProjects with MIT License 5 votes vote down vote up
private void readJournal() throws IOException {
  BufferedSource source = Okio.buffer(fileSystem.source(journalFile));
  try {
    String magic = source.readUtf8LineStrict();
    String version = source.readUtf8LineStrict();
    String appVersionString = source.readUtf8LineStrict();
    String valueCountString = source.readUtf8LineStrict();
    String blank = source.readUtf8LineStrict();
    if (!MAGIC.equals(magic)
        || !VERSION_1.equals(version)
        || !Integer.toString(appVersion).equals(appVersionString)
        || !Integer.toString(valueCount).equals(valueCountString)
        || !"".equals(blank)) {
      throw new IOException("unexpected journal header: [" + magic + ", " + version + ", "
          + valueCountString + ", " + blank + "]");
    }

    int lineCount = 0;
    while (true) {
      try {
        readJournalLine(source.readUtf8LineStrict());
        lineCount++;
      } catch (EOFException endOfJournal) {
        break;
      }
    }
    redundantOpCount = lineCount - lruEntries.size();

    // If we ended on a truncated line, rebuild the journal before appending to it.
    if (!source.exhausted()) {
      rebuildJournal();
    } else {
      journalWriter = newJournalWriter();
    }
  } finally {
    Util.closeQuietly(source);
  }
}
 
Example #26
Source File: InputStreamRequestBody.java    From domo-java-sdk with MIT License 5 votes vote down vote up
@Override
public void writeTo(BufferedSink sink) throws IOException {
    Source source = null;
    try {
        source = Okio.source(inputStream);
        sink.writeAll(source);
    } finally {
        Util.closeQuietly(source);
    }
}
 
Example #27
Source File: RequestBodyUtils.java    From RxEasyHttp with Apache License 2.0 5 votes vote down vote up
public static RequestBody create(final MediaType mediaType, final InputStream inputStream) {
    return new RequestBody() {
        @Override
        public MediaType contentType() {
            return mediaType;
        }

        @Override
        public long contentLength() {
            try {
                return inputStream.available();
            } catch (IOException e) {
                return 0;
            }
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            Source source = null;
            try {
                source = Okio.source(inputStream);
                sink.writeAll(source);
            } finally {
                Util.closeQuietly(source);
            }
        }
    };
}
 
Example #28
Source File: RealConnection.java    From AndroidProjects with MIT License 5 votes vote down vote up
/**
 * Returns a request that creates a TLS tunnel via an HTTP proxy. Everything in the tunnel request
 * is sent unencrypted to the proxy server, so tunnels include only the minimum set of headers.
 * This avoids sending potentially sensitive data like HTTP cookies to the proxy unencrypted.
 */
private Request createTunnelRequest() {
  return new Request.Builder()
      .url(route.address().url())
      .header("Host", Util.hostHeader(route.address().url(), true))
      .header("Proxy-Connection", "Keep-Alive") // For HTTP/1.0 proxies like Squid.
      .header("User-Agent", Version.userAgent())
      .build();
}
 
Example #29
Source File: TLSCompactHelper.java    From Mysplash with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static OkHttpClient getOKHttpClient() {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.connectTimeout(15, TimeUnit.SECONDS)
            .readTimeout(15, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        try {
            SSLContext sc = SSLContext.getInstance("TLSv1.2");
            sc.init(null, null, null);
            builder.sslSocketFactory(
                    new Tls12SocketFactory(sc.getSocketFactory()),
                    Util.platformTrustManager()
            );

            ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                    .tlsVersions(TlsVersion.TLS_1_2)
                    .build();

            List<ConnectionSpec> specs = new ArrayList<>();
            specs.add(cs);
            specs.add(ConnectionSpec.COMPATIBLE_TLS);
            specs.add(ConnectionSpec.CLEARTEXT);

            builder.connectionSpecs(specs)
                    .followRedirects(true)
                    .followSslRedirects(true)
                    .retryOnConnectionFailure(true)
                    .cache(null);
        } catch (Exception e) {
            Log.e("OkHttpTLSCompat", "Error while setting TLS 1.2", e);
        }
    }
    return builder.build();
}
 
Example #30
Source File: Handshake.java    From styT with Apache License 2.0 5 votes vote down vote up
@Override public boolean equals(Object other) {
  if (!(other instanceof Handshake)) return false;
  Handshake that = (Handshake) other;
  return Util.equal(cipherSuite, that.cipherSuite)
      && cipherSuite.equals(that.cipherSuite)
      && peerCertificates.equals(that.peerCertificates)
      && localCertificates.equals(that.localCertificates);
}