okhttp3.internal.platform.Platform Java Examples

The following examples show how to use okhttp3.internal.platform.Platform. 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: RealConnection.java    From AndroidProjects with MIT License 6 votes vote down vote up
/** Does all the work necessary to build a full HTTP or HTTPS connection on a raw socket. */
private void connectSocket(int connectTimeout, int readTimeout) throws IOException {
  Proxy proxy = route.proxy();
  Address address = route.address();

  rawSocket = proxy.type() == Proxy.Type.DIRECT || proxy.type() == Proxy.Type.HTTP
      ? address.socketFactory().createSocket()
      : new Socket(proxy);

  rawSocket.setSoTimeout(readTimeout);
  try {
    Platform.get().connectSocket(rawSocket, route.socketAddress(), connectTimeout);
  } catch (ConnectException e) {
    ConnectException ce = new ConnectException("Failed to connect to " + route.socketAddress());
    ce.initCause(e);
    throw ce;
  }
  source = Okio.buffer(Okio.source(rawSocket));
  sink = Okio.buffer(Okio.sink(rawSocket));
}
 
Example #2
Source File: RealCall.java    From styT with Apache License 2.0 6 votes vote down vote up
@Override protected void execute() {
  boolean signalledCallback = false;
  try {
    Response response = getResponseWithInterceptorChain();
    if (retryAndFollowUpInterceptor.isCanceled()) {
      signalledCallback = true;
      responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
    } else {
      signalledCallback = true;
      responseCallback.onResponse(RealCall.this, response);
    }
  } catch (IOException e) {
    if (signalledCallback) {
      // Do not signal the callback twice!
      Platform.get().log(INFO, "Callback failure for " + toLoggableString(), e);
    } else {
      responseCallback.onFailure(RealCall.this, e);
    }
  } finally {
    client.dispatcher().finished(this);
  }
}
 
Example #3
Source File: RealCall.java    From AndroidProjects with MIT License 6 votes vote down vote up
@Override
protected void execute() {
    boolean signalledCallback = false;
    try {
        Response response = getResponseWithInterceptorChain();
        if (retryAndFollowUpInterceptor.isCanceled()) {
            signalledCallback = true;
            responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
        } else {
            signalledCallback = true;
            responseCallback.onResponse(RealCall.this, response);
        }
    } catch (IOException e) {
        if (signalledCallback) {
            // Do not signal the callback twice!
            Platform.get().log(INFO, "Callback failure for " + toLoggableString(), e);
        } else {
            responseCallback.onFailure(RealCall.this, e);
        }
    } finally {
        client.dispatcher().finished(this);
    }
}
 
Example #4
Source File: RealConnection.java    From styT with Apache License 2.0 6 votes vote down vote up
/** Does all the work necessary to build a full HTTP or HTTPS connection on a raw socket. */
private void connectSocket(int connectTimeout, int readTimeout) throws IOException {
  Proxy proxy = route.proxy();
  Address address = route.address();

  rawSocket = proxy.type() == Proxy.Type.DIRECT || proxy.type() == Proxy.Type.HTTP
      ? address.socketFactory().createSocket()
      : new Socket(proxy);

  rawSocket.setSoTimeout(readTimeout);
  try {
    Platform.get().connectSocket(rawSocket, route.socketAddress(), connectTimeout);
  } catch (ConnectException e) {
    ConnectException ce = new ConnectException("Failed to connect to " + route.socketAddress());
    ce.initCause(e);
    throw ce;
  }
  source = Okio.buffer(Okio.source(rawSocket));
  sink = Okio.buffer(Okio.sink(rawSocket));
}
 
Example #5
Source File: ApiClient.java    From GracefulMovies with Apache License 2.0 6 votes vote down vote up
public ApiClient() {
    mRetrofitBuilder = new Retrofit.Builder()
            .baseUrl("https://api-m.mtime.cn/")
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create());

    mOkHttpClientBuilder = new OkHttpClient.Builder();
    mOkHttpClientBuilder.connectTimeout(15, TimeUnit.SECONDS);
    if (BuildConfig.DEBUG) {
        mOkHttpClientBuilder.addNetworkInterceptor(
                new LoggingInterceptor.Builder()
                        .loggable(BuildConfig.DEBUG)
                        .setLevel(Level.BODY)
                        .log(Platform.INFO)
                        .request("Request")
                        .response("Response")
                        .build()
        );
    }
}
 
Example #6
Source File: QuotePreservingCookieJar.java    From td-ameritrade-client with Apache License 2.0 5 votes vote down vote up
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
    // The RI passes all headers. We don't have 'em, so we don't pass 'em!
    Map<String, List<String>> headers = Collections.emptyMap();
    Map<String, List<String>> cookieHeaders;
    try {
        cookieHeaders = cookieHandler.get(url.uri(), headers);
    } catch (IOException e) {
        Platform.get().log(WARN, "Loading cookies failed for " + url.resolve("/..."), e);
        return Collections.emptyList();
    }

    List<Cookie> cookies = null;
    for (Map.Entry<String, List<String>> entry : cookieHeaders.entrySet()) {
        String key = entry.getKey();
        if (("Cookie".equalsIgnoreCase(key) || "Cookie2".equalsIgnoreCase(key))
                && !entry.getValue().isEmpty()) {
            for (String header : entry.getValue()) {
                if (cookies == null) cookies = new ArrayList<>();
                cookies.addAll(decodeHeaderAsJavaNetCookies(url, header));
            }
        }
    }

    return cookies != null
            ? Collections.unmodifiableList(cookies)
            : Collections.emptyList();
}
 
Example #7
Source File: WebSocketRecorder.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * On open.
 *
 * @param webSocket the web socket
 * @param response the response
 */
@Override
public void onOpen(WebSocket webSocket, Response response) {
  Platform.get().log(Platform.INFO, "[WS " + name + "] onOpen", null);

  WebSocketListener delegate = this.delegate;
  if (delegate != null) {
    this.delegate = null;
    delegate.onOpen(webSocket, response);
  } else {
    events.add(new Open(webSocket, response));
  }
}
 
Example #8
Source File: ConnectionPool.java    From styT with Apache License 2.0 5 votes vote down vote up
/**
 * Prunes any leaked allocations and then returns the number of remaining live allocations on
 * {@code connection}. Allocations are leaked if the connection is tracking them but the
 * application code has abandoned them. Leak detection is imprecise and relies on garbage
 * collection.
 */
private int pruneAndGetAllocationCount(RealConnection connection, long now) {
  List<Reference<StreamAllocation>> references = connection.allocations;
  for (int i = 0; i < references.size(); ) {
    Reference<StreamAllocation> reference = references.get(i);

    if (reference.get() != null) {
      i++;
      continue;
    }

    // We've discovered a leaked allocation. This is an application bug.
    StreamAllocation.StreamAllocationReference streamAllocRef =
        (StreamAllocation.StreamAllocationReference) reference;
    String message = "A connection to " + connection.route().address().url()
        + " was leaked. Did you forget to close a response body?";
    Platform.get().logCloseableLeak(message, streamAllocRef.callStackTrace);

    references.remove(i);
    connection.noNewStreams = true;

    // If this was the last allocation, the connection is eligible for immediate eviction.
    if (references.isEmpty()) {
      connection.idleAtNanos = now - keepAliveDurationNs;
      return 0;
    }
  }

  return references.size();
}
 
Example #9
Source File: ConnectionPool.java    From AndroidProjects with MIT License 5 votes vote down vote up
/**
 * Prunes any leaked allocations and then returns the number of remaining live allocations on
 * {@code connection}. Allocations are leaked if the connection is tracking them but the
 * application code has abandoned them. Leak detection is imprecise and relies on garbage
 * collection.
 */
private int pruneAndGetAllocationCount(RealConnection connection, long now) {
    List<Reference<StreamAllocation>> references = connection.allocations;
    for (int i = 0; i < references.size(); ) {
        Reference<StreamAllocation> reference = references.get(i);

        if (reference.get() != null) {
            i++;
            continue;
        }

        // We've discovered a leaked allocation. This is an application bug.
        StreamAllocation.StreamAllocationReference streamAllocRef =
                (StreamAllocation.StreamAllocationReference) reference;
        String message = "A connection to " + connection.route().address().url()
                + " was leaked. Did you forget to close a response body?";
        Platform.get().logCloseableLeak(message, streamAllocRef.callStackTrace);

        references.remove(i);
        connection.noNewStreams = true;

        // If this was the last allocation, the connection is eligible for immediate eviction.
        if (references.isEmpty()) {
            connection.idleAtNanos = now - keepAliveDurationNs;
            return 0;
        }
    }

    return references.size();
}
 
Example #10
Source File: WebSocketRecorder.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * On message.
 *
 * @param webSocket the web socket
 * @param bytes the bytes
 */
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
  Platform.get().log(Platform.INFO, "[WS " + name + "] onMessage", null);

  WebSocketListener delegate = this.delegate;
  if (delegate != null) {
    this.delegate = null;
    delegate.onMessage(webSocket, bytes);
  } else {
    Message event = new Message(bytes);
    events.add(event);
  }
}
 
Example #11
Source File: QuotePreservingCookieJar.java    From td-ameritrade-client with Apache License 2.0 5 votes vote down vote up
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
    if (cookieHandler != null) {
        List<String> cookieStrings = new ArrayList<>();
        for (Cookie cookie : cookies) {
            cookieStrings.add(cookie.toString().replaceAll("; domain=", "; domain=."));
        }
        Map<String, List<String>> multimap = Collections.singletonMap("Set-Cookie", cookieStrings);
        try {
            cookieHandler.put(url.uri(), multimap);
        } catch (IOException e) {
            Platform.get().log(WARN, "Saving cookies failed for " + url.resolve("/..."), e);
        }
    }
}
 
Example #12
Source File: WebSocketRecorder.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * On message.
 *
 * @param webSocket the web socket
 * @param text the text
 */
@Override
public void onMessage(WebSocket webSocket, String text) {
  Platform.get().log(Platform.INFO, "[WS " + name + "] onMessage", null);

  WebSocketListener delegate = this.delegate;
  if (delegate != null) {
    this.delegate = null;
    delegate.onMessage(webSocket, text);
  } else {
    Message event = new Message(text);
    events.add(event);
  }
}
 
Example #13
Source File: WebSocketRecorder.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * On closing.
 *
 * @param webSocket the web socket
 * @param code the code
 * @param reason the reason
 */
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
  Platform.get().log(Platform.INFO, "[WS " + name + "] onClose " + code, null);

  WebSocketListener delegate = this.delegate;
  if (delegate != null) {
    this.delegate = null;
    delegate.onClosing(webSocket, code, reason);
  } else {
    events.add(new Closing(code, reason));
  }
}
 
Example #14
Source File: PublicSuffixDatabase.java    From styT with Apache License 2.0 5 votes vote down vote up
private void readTheList() {
  byte[] publicSuffixListBytes = null;
  byte[] publicSuffixExceptionListBytes = null;

  InputStream is = PublicSuffixDatabase.class.getClassLoader().getResourceAsStream(
      PUBLIC_SUFFIX_RESOURCE);

  if (is != null) {
    BufferedSource bufferedSource = Okio.buffer(new GzipSource(Okio.source(is)));
    try {
      int totalBytes = bufferedSource.readInt();
      publicSuffixListBytes = new byte[totalBytes];
      bufferedSource.readFully(publicSuffixListBytes);

      int totalExceptionBytes = bufferedSource.readInt();
      publicSuffixExceptionListBytes = new byte[totalExceptionBytes];
      bufferedSource.readFully(publicSuffixExceptionListBytes);
    } catch (IOException e) {
      Platform.get().log(Platform.WARN, "Failed to read public suffix list", e);
      publicSuffixListBytes = null;
      publicSuffixExceptionListBytes = null;
    } finally {
      closeQuietly(bufferedSource);
    }
  }

  synchronized (this) {
    this.publicSuffixListBytes = publicSuffixListBytes;
    this.publicSuffixExceptionListBytes = publicSuffixExceptionListBytes;
  }

  readCompleteLatch.countDown();
}
 
Example #15
Source File: WebSocketRecorder.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * On closed.
 *
 * @param webSocket the web socket
 * @param code the code
 * @param reason the reason
 */
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
  Platform.get().log(Platform.INFO, "[WS " + name + "] onClose " + code, null);

  WebSocketListener delegate = this.delegate;
  if (delegate != null) {
    this.delegate = null;
    delegate.onClosed(webSocket, code, reason);
  } else {
    events.add(new Closed(code, reason));
  }
}
 
Example #16
Source File: WebSocketRecorder.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * On failure.
 *
 * @param webSocket the web socket
 * @param t the t
 * @param response the response
 */
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
  Platform.get().log(Platform.INFO, "[WS " + name + "] onFailure", t);

  WebSocketListener delegate = this.delegate;
  if (delegate != null) {
    this.delegate = null;
    delegate.onFailure(webSocket, t, response);
  } else {
    events.add(new Failure(t, response));
  }
}
 
Example #17
Source File: RealCall.java    From AndroidProjects with MIT License 4 votes vote down vote up
private void captureCallStackTrace() {
    Object callStackTrace = Platform.get().getStackTraceForCloseable("response.body().close()");
    retryAndFollowUpInterceptor.setCallStackTrace(callStackTrace);
}
 
Example #18
Source File: WeChatSendRedPack.java    From WeChatSendRedPack with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {


        //具体参数查看具体实体类,实体类中的的参数参考微信的红包发放接口,这里你直接用map,进行设置参数也可以。。。
        SendRedPack sendRedPack = new SendRedPack(
                "随机字符串不超过32位",
                "随机订单号,不超过32位",
                "商户号",
                "公众号appid",
                "桑博",
                "填写接受人的openid",
                100,
                1,
                "萌萌哒",
                "127.0.0.1",
                "桑博红包",
                "桑博",
                "PRODUCT_5"
        );


        //将实体类转换为url形式
        String urlParamsByMap = Tool.getUrlParamsByMap(Tool.toMap(sendRedPack));
        //拼接我们再前期准备好的API密钥,前期准备第5条
        urlParamsByMap += "&key=填写API密钥";
        //进行签名,需要说明的是,如果内容包含中文的话,要使用utf-8进行md5签名,不然会签名错误
        String sign = Tool.parseStrToMd5L32(urlParamsByMap).toUpperCase();
        sendRedPack.setSign(sign);
        //微信要求按照参数名ASCII字典序排序,这里巧用treeMap进行字典排序
        TreeMap treeMap = new TreeMap(Tool.toMap(sendRedPack));
        //然后转换成xml格式
        String soapRequestData = Tool.getSoapRequestData(treeMap);
        //发起请求前准备
        RequestBody body = RequestBody.create(MediaType.parse("text/xml;charset=UTF-8"), soapRequestData);
        Request request = new Request.Builder()
                .url("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack")
                .post(body)
                .build();
        //为http请求设置证书
        SSLSocketFactory socketFactory = getSSL().getSocketFactory();
        X509TrustManager x509TrustManager = Platform.get().trustManager(socketFactory);
        OkHttpClient okHttpClient = new OkHttpClient.Builder().sslSocketFactory(socketFactory, x509TrustManager).build();
        //得到输出内容
        Response response = okHttpClient.newCall(request).execute();
        String content = response.body().string();
        System.out.println(content);

    }
 
Example #19
Source File: RealConnection.java    From AndroidProjects with MIT License 4 votes vote down vote up
public void connect(
    int connectTimeout, int readTimeout, int writeTimeout, boolean connectionRetryEnabled) {
  if (protocol != null) throw new IllegalStateException("already connected");

  RouteException routeException = null;
  List<ConnectionSpec> connectionSpecs = route.address().connectionSpecs();
  ConnectionSpecSelector connectionSpecSelector = new ConnectionSpecSelector(connectionSpecs);

  if (route.address().sslSocketFactory() == null) {
    if (!connectionSpecs.contains(ConnectionSpec.CLEARTEXT)) {
      throw new RouteException(new UnknownServiceException(
          "CLEARTEXT communication not enabled for client"));
    }
    String host = route.address().url().host();
    if (!Platform.get().isCleartextTrafficPermitted(host)) {
      throw new RouteException(new UnknownServiceException(
          "CLEARTEXT communication to " + host + " not permitted by network security policy"));
    }
  }

  while (true) {
    try {
      if (route.requiresTunnel()) {
        connectTunnel(connectTimeout, readTimeout, writeTimeout);
      } else {
        connectSocket(connectTimeout, readTimeout);
      }
      establishProtocol(connectionSpecSelector);
      break;
    } catch (IOException e) {
      closeQuietly(socket);
      closeQuietly(rawSocket);
      socket = null;
      rawSocket = null;
      source = null;
      sink = null;
      handshake = null;
      protocol = null;
      http2Connection = null;

      if (routeException == null) {
        routeException = new RouteException(e);
      } else {
        routeException.addConnectException(e);
      }

      if (!connectionRetryEnabled || !connectionSpecSelector.connectionFailed(e)) {
        throw routeException;
      }
    }
  }

  if (http2Connection != null) {
    synchronized (connectionPool) {
      allocationLimit = http2Connection.maxConcurrentStreams();
    }
  }
}
 
Example #20
Source File: Http2Connection.java    From AndroidProjects with MIT License 4 votes vote down vote up
@Override public void headers(boolean inFinished, int streamId, int associatedStreamId,
    List<Header> headerBlock) {
  if (pushedStream(streamId)) {
    pushHeadersLater(streamId, headerBlock, inFinished);
    return;
  }
  Http2Stream stream;
  synchronized (Http2Connection.this) {
    // If we're shutdown, don't bother with this stream.
    if (shutdown) return;

    stream = getStream(streamId);

    if (stream == null) {
      // If the stream ID is less than the last created ID, assume it's already closed.
      if (streamId <= lastGoodStreamId) return;

      // If the stream ID is in the client's namespace, assume it's already closed.
      if (streamId % 2 == nextStreamId % 2) return;

      // Create a stream.
      final Http2Stream newStream = new Http2Stream(streamId, Http2Connection.this,
          false, inFinished, headerBlock);
      lastGoodStreamId = streamId;
      streams.put(streamId, newStream);
      executor.execute(new NamedRunnable("OkHttp %s stream %d", hostname, streamId) {
        @Override public void execute() {
          try {
            listener.onStream(newStream);
          } catch (IOException e) {
            Platform.get().log(INFO, "Http2Connection.Listener failure for " + hostname, e);
            try {
              newStream.close(ErrorCode.PROTOCOL_ERROR);
            } catch (IOException ignored) {
            }
          }
        }
      });
      return;
    }
  }

  // Update an existing stream.
  stream.receiveHeaders(headerBlock);
  if (inFinished) stream.receiveFin();
}
 
Example #21
Source File: CertificateChainCleaner.java    From AndroidProjects with MIT License 4 votes vote down vote up
public static CertificateChainCleaner get(X509TrustManager trustManager) {
  return Platform.get().buildCertificateChainCleaner(trustManager);
}
 
Example #22
Source File: RockBaseLogInterceptor.java    From RxJava2RetrofitDemo with Apache License 2.0 4 votes vote down vote up
@Override
public void log(String message) {
    Platform.get().log(INFO, message, null);
}
 
Example #23
Source File: RealConnection.java    From styT with Apache License 2.0 4 votes vote down vote up
public void connect(
    int connectTimeout, int readTimeout, int writeTimeout, boolean connectionRetryEnabled) {
  if (protocol != null) throw new IllegalStateException("already connected");

  RouteException routeException = null;
  List<ConnectionSpec> connectionSpecs = route.address().connectionSpecs();
  ConnectionSpecSelector connectionSpecSelector = new ConnectionSpecSelector(connectionSpecs);

  if (route.address().sslSocketFactory() == null) {
    if (!connectionSpecs.contains(ConnectionSpec.CLEARTEXT)) {
      throw new RouteException(new UnknownServiceException(
          "CLEARTEXT communication not enabled for client"));
    }
    String host = route.address().url().host();
    if (!Platform.get().isCleartextTrafficPermitted(host)) {
      throw new RouteException(new UnknownServiceException(
          "CLEARTEXT communication to " + host + " not permitted by network security policy"));
    }
  }

  while (true) {
    try {
      if (route.requiresTunnel()) {
        connectTunnel(connectTimeout, readTimeout, writeTimeout);
      } else {
        connectSocket(connectTimeout, readTimeout);
      }
      establishProtocol(connectionSpecSelector);
      break;
    } catch (IOException e) {
      closeQuietly(socket);
      closeQuietly(rawSocket);
      socket = null;
      rawSocket = null;
      source = null;
      sink = null;
      handshake = null;
      protocol = null;
      http2Connection = null;

      if (routeException == null) {
        routeException = new RouteException(e);
      } else {
        routeException.addConnectException(e);
      }

      if (!connectionRetryEnabled || !connectionSpecSelector.connectionFailed(e)) {
        throw routeException;
      }
    }
  }

  if (http2Connection != null) {
    synchronized (connectionPool) {
      allocationLimit = http2Connection.maxConcurrentStreams();
    }
  }
}
 
Example #24
Source File: Http2Connection.java    From styT with Apache License 2.0 4 votes vote down vote up
@Override public void headers(boolean inFinished, int streamId, int associatedStreamId,
    List<Header> headerBlock) {
  if (pushedStream(streamId)) {
    pushHeadersLater(streamId, headerBlock, inFinished);
    return;
  }
  Http2Stream stream;
  synchronized (Http2Connection.this) {
    // If we're shutdown, don't bother with this stream.
    if (shutdown) return;

    stream = getStream(streamId);

    if (stream == null) {
      // If the stream ID is less than the last created ID, assume it's already closed.
      if (streamId <= lastGoodStreamId) return;

      // If the stream ID is in the client's namespace, assume it's already closed.
      if (streamId % 2 == nextStreamId % 2) return;

      // Create a stream.
      final Http2Stream newStream = new Http2Stream(streamId, Http2Connection.this,
          false, inFinished, headerBlock);
      lastGoodStreamId = streamId;
      streams.put(streamId, newStream);
      executor.execute(new NamedRunnable("OkHttp %s stream %d", hostname, streamId) {
        @Override public void execute() {
          try {
            listener.onStream(newStream);
          } catch (IOException e) {
            Platform.get().log(INFO, "Http2Connection.Listener failure for " + hostname, e);
            try {
              newStream.close(ErrorCode.PROTOCOL_ERROR);
            } catch (IOException ignored) {
            }
          }
        }
      });
      return;
    }
  }

  // Update an existing stream.
  stream.receiveHeaders(headerBlock);
  if (inFinished) stream.receiveFin();
}
 
Example #25
Source File: CertificateChainCleaner.java    From styT with Apache License 2.0 4 votes vote down vote up
public static CertificateChainCleaner get(X509TrustManager trustManager) {
  return Platform.get().buildCertificateChainCleaner(trustManager);
}
 
Example #26
Source File: RealCall.java    From styT with Apache License 2.0 4 votes vote down vote up
private void captureCallStackTrace() {
  Object callStackTrace = Platform.get().getStackTraceForCloseable("response.body().close()");
  retryAndFollowUpInterceptor.setCallStackTrace(callStackTrace);
}