com.squareup.okhttp.internal.Util类的使用及代码示例

x33g5p2x  于2022-02-01 转载在 其他  
字(11.7k)|赞(0)|评价(0)|浏览(193)

本文整理了Java中com.squareup.okhttp.internal.Util类的一些代码示例,展示了Util类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Util类的具体详情如下:
包路径:com.squareup.okhttp.internal.Util
类名称:Util

Util介绍

暂无

代码示例

代码示例来源:origin: aa112901/remusic

public static FilterInputStream getFromCache(Context context, String url) throws Exception {
  //  File cacheDirectory = new File("/storage/emulated/0/Android/data/com.name.demo .dev/cache/HttpCache");
  File cacheDirectory = context.getExternalCacheDir();
  DiskLruCache cache = DiskLruCache.create(FileSystem.SYSTEM, cacheDirectory, 201105, 2, 1024 * 1024 * 30);
  cache.flush();
  String key = Util.md5Hex(url);
  final DiskLruCache.Snapshot snapshot;
  try {
    snapshot = cache.get(key);
    if (snapshot == null) {
      return null;
    }
  } catch (IOException e) {
    return null;
  }
  okio.Source source = snapshot.getSource(1);
  BufferedSource metadata = Okio.buffer(source);
  FilterInputStream bodyIn = new FilterInputStream(metadata.inputStream()) {
    @Override
    public void close() throws IOException {
      snapshot.close();
      super.close();
    }
  };
  return bodyIn;
}

代码示例来源:origin: evernote/evernote-sdk-android

@Override
  public void close() {
    Util.closeQuietly(mResponseBody);
    mResponseBody = null;
  }
}

代码示例来源:origin: com.squareup.okhttp/mockwebserver

private void handleWebSocketUpgrade(Socket socket, BufferedSource source, BufferedSink sink,
  RecordedRequest request, MockResponse response) throws IOException {
 String key = request.getHeader("Sec-WebSocket-Key");
 String acceptKey = Util.shaBase64(key + WebSocketProtocol.ACCEPT_MAGIC);
 response.setHeader("Sec-WebSocket-Accept", acceptKey);
     Util.threadFactory(String.format("MockWebServer %s WebSocket", request.getPath()),
       true));
 replyExecutor.allowCoreThreadTimeOut(true);
 Util.closeQuietly(sink);
 Util.closeQuietly(source);

代码示例来源:origin: com.squareup.okhttp/mockwebserver

/**
 * Indicates the protocols supported by ALPN on incoming HTTPS
 * connections. This list is ignored when
 * {@link #setProtocolNegotiationEnabled negotiation is disabled}.
 *
 * @param protocols the protocols to use, in order of preference. The list
 *     must contain {@linkplain Protocol#HTTP_1_1}. It must not contain null.
 */
public void setProtocols(List<Protocol> protocols) {
 protocols = Util.immutableList(protocols);
 if (!protocols.contains(Protocol.HTTP_1_1)) {
  throw new IllegalArgumentException("protocols doesn't contain http/1.1: " + protocols);
 }
 if (protocols.contains(null)) {
  throw new IllegalArgumentException("protocols must not contain null");
 }
 this.protocols = protocols;
}

代码示例来源:origin: com.squareup.okhttp/okhttp-ws

private void createWebSocket(Response response, WebSocketListener listener) throws IOException {
 if (response.code() != 101) {
  Util.closeQuietly(response.body());
  throw new ProtocolException("Expected HTTP 101 response but was '"
    + response.code()
 String acceptExpected = Util.shaBase64(key + WebSocketProtocol.ACCEPT_MAGIC);
 if (!acceptExpected.equals(headerAccept)) {
  throw new ProtocolException("Expected 'Sec-WebSocket-Accept' header value '"

代码示例来源:origin: com.squareup.okhttp/okhttp-ws

static RealWebSocket create(StreamAllocation streamAllocation, Response response,
  Random random, WebSocketListener listener) {
 String url = response.request().urlString();
 ThreadPoolExecutor replyExecutor =
   new ThreadPoolExecutor(1, 1, 1, SECONDS, new LinkedBlockingDeque<Runnable>(),
     Util.threadFactory(String.format("OkHttp %s WebSocket", url), true));
 replyExecutor.allowCoreThreadTimeOut(true);
 return new StreamWebSocket(streamAllocation, random, replyExecutor, listener, url);
}

代码示例来源:origin: apiman/apiman

@Override public final Permission getPermission() throws IOException {
 String hostName = getURL().getHost();
 int hostPort = Util.getEffectivePort(getURL());
 if (usingProxy()) {
  InetSocketAddress proxyAddress = (InetSocketAddress) client.getProxy().address();
  hostName = proxyAddress.getHostName();
  hostPort = proxyAddress.getPort();
 }
 return new SocketPermission(hostName + ":" + hostPort, "connect, resolve");
}

代码示例来源:origin: com.squareup.okhttp/okhttp-urlconnection

private String defaultUserAgent() {
 String agent = System.getProperty("http.agent");
 return agent != null ? Util.toHumanReadableAscii(agent) : Version.userAgent();
}

代码示例来源:origin: evernote/evernote-sdk-android

private static void readFile(File file, byte[] buffer, int length) throws IOException {
  InputStream inputStream = null;
  try {
    inputStream = new FileInputStream(file);
    int read = 0;
    int offset = 0;
    while (length > 0 && read >= 0) {
      read = inputStream.read(buffer, offset, length);
      offset += read;
      length -= read;
    }
  } finally {
    Util.closeQuietly(inputStream);
  }
}

代码示例来源:origin: apiman/apiman

/**
 * Constructor.
 * @param metricsServer
 */
public HawkularMetricsClient(URL metricsServer) {
  this.serverUrl = metricsServer;
  httpClient = new OkHttpClient();
  httpClient.setReadTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.SECONDS);
  httpClient.setWriteTimeout(DEFAULT_WRITE_TIMEOUT, TimeUnit.SECONDS);
  httpClient.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT, TimeUnit.SECONDS);
  httpClient.setFollowRedirects(true);
  httpClient.setFollowSslRedirects(true);
  httpClient.setProxySelector(ProxySelector.getDefault());
  httpClient.setCookieHandler(CookieHandler.getDefault());
  httpClient.setCertificatePinner(CertificatePinner.DEFAULT);
  httpClient.setAuthenticator(AuthenticatorAdapter.INSTANCE);
  httpClient.setConnectionPool(ConnectionPool.getDefault());
  httpClient.setProtocols(Util.immutableList(Protocol.HTTP_1_1));
  httpClient.setConnectionSpecs(DEFAULT_CONNECTION_SPECS);
  httpClient.setSocketFactory(SocketFactory.getDefault());
  Internal.instance.setNetwork(httpClient, Network.DEFAULT);
}

代码示例来源:origin: com.squareup.okhttp/mockwebserver

started = true;
executor = Executors.newCachedThreadPool(Util.threadFactory("MockWebServer", false));
this.inetSocketAddress = inetSocketAddress;
serverSocket = serverSocketFactory.createServerSocket();

代码示例来源:origin: io.apiman/apiman-gateway-platforms-servlet

@Override public final Permission getPermission() throws IOException {
 String hostName = getURL().getHost();
 int hostPort = Util.getEffectivePort(getURL());
 if (usingProxy()) {
  InetSocketAddress proxyAddress = (InetSocketAddress) client.getProxy().address();
  hostName = proxyAddress.getHostName();
  hostPort = proxyAddress.getPort();
 }
 return new SocketPermission(hostName + ":" + hostPort, "connect, resolve");
}

代码示例来源:origin: evernote/evernote-sdk-android

@Override
public void close() throws IOException {
  if (!mClosed) {
    Util.closeQuietly(mFileOutputStream);
    mByteArrayOutputStream.reset();
    mClosed = true;
  }
}

代码示例来源:origin: io.apiman/apiman-common-net

/**
 * Constructor.
 * @param metricsServer
 */
public HawkularMetricsClient(URL metricsServer) {
  this.serverUrl = metricsServer;
  httpClient = new OkHttpClient();
  httpClient.setReadTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.SECONDS);
  httpClient.setWriteTimeout(DEFAULT_WRITE_TIMEOUT, TimeUnit.SECONDS);
  httpClient.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT, TimeUnit.SECONDS);
  httpClient.setFollowRedirects(true);
  httpClient.setFollowSslRedirects(true);
  httpClient.setProxySelector(ProxySelector.getDefault());
  httpClient.setCookieHandler(CookieHandler.getDefault());
  httpClient.setCertificatePinner(CertificatePinner.DEFAULT);
  httpClient.setAuthenticator(AuthenticatorAdapter.INSTANCE);
  httpClient.setConnectionPool(ConnectionPool.getDefault());
  httpClient.setProtocols(Util.immutableList(Protocol.HTTP_1_1));
  httpClient.setConnectionSpecs(DEFAULT_CONNECTION_SPECS);
  httpClient.setSocketFactory(SocketFactory.getDefault());
  Internal.instance.setNetwork(httpClient, Network.DEFAULT);
}

代码示例来源:origin: com.squareup.okhttp/mockwebserver

@Override protected void execute() {
 try {
  logger.info(MockWebServer.this + " starting to accept connections");
  acceptConnections();
 } catch (Throwable e) {
  logger.log(Level.WARNING, MockWebServer.this + " failed unexpectedly", e);
 }
 // Release all sockets and all threads, even if any close fails.
 Util.closeQuietly(serverSocket);
 for (Iterator<Socket> s = openClientSockets.iterator(); s.hasNext(); ) {
  Util.closeQuietly(s.next());
  s.remove();
 }
 for (Iterator<FramedConnection> s = openFramedConnections.iterator(); s.hasNext(); ) {
  Util.closeQuietly(s.next());
  s.remove();
 }
 executor.shutdown();
}

代码示例来源:origin: apiman/apiman

/**
 * @return a new http client
 */
private OkHttpClient createHttpClient() {
  OkHttpClient client = new OkHttpClient();
  client.setReadTimeout(connectorOptions.getReadTimeout(), TimeUnit.SECONDS);
  client.setWriteTimeout(connectorOptions.getWriteTimeout(), TimeUnit.SECONDS);
  client.setConnectTimeout(connectorOptions.getConnectTimeout(), TimeUnit.SECONDS);
  client.setFollowRedirects(connectorOptions.isFollowRedirects());
  client.setFollowSslRedirects(connectorOptions.isFollowRedirects());
  client.setProxySelector(ProxySelector.getDefault());
  client.setCookieHandler(CookieHandler.getDefault());
  client.setCertificatePinner(CertificatePinner.DEFAULT);
  client.setAuthenticator(AuthenticatorAdapter.INSTANCE);
  client.setConnectionPool(ConnectionPool.getDefault());
  client.setProtocols(Util.immutableList(Protocol.HTTP_1_1));
  client.setConnectionSpecs(DEFAULT_CONNECTION_SPECS);
  client.setSocketFactory(SocketFactory.getDefault());
  Internal.instance.setNetwork(client, Network.DEFAULT);
  return client;
}

代码示例来源:origin: com.squareup.okhttp/mockwebserver

private void run() throws Exception {
 ServerSocket serverSocket = new ServerSocket(8888);
 serverSocket.setReuseAddress(true);
 while (true) {
  Socket socket = null;
  try {
   socket = serverSocket.accept();
   SSLSocket sslSocket = doSsl(socket);
   String protocolString = Platform.get().getSelectedProtocol(sslSocket);
   Protocol protocol = protocolString != null ? Protocol.get(protocolString) : null;
   if (protocol == null || !framedProtocols.contains(protocol)) {
    throw new ProtocolException("Protocol " + protocol + " unsupported");
   }
   FramedConnection framedConnection = new FramedConnection.Builder(false)
     .socket(sslSocket)
     .protocol(protocol)
     .listener(this)
     .build();
   framedConnection.sendConnectionPreface();
  } catch (IOException e) {
   logger.log(Level.INFO, "FramedServer connection failure: " + e);
   Util.closeQuietly(socket);
  } catch (Exception e) {
   logger.log(Level.WARNING, "FramedServer unexpected failure", e);
   Util.closeQuietly(socket);
  }
 }
}

代码示例来源:origin: io.apiman/apiman-gateway-platforms-servlet

/**
 * @return a new http client
 */
private OkHttpClient createHttpClient() {
  OkHttpClient client = new OkHttpClient();
  client.setReadTimeout(connectorOptions.getReadTimeout(), TimeUnit.SECONDS);
  client.setWriteTimeout(connectorOptions.getWriteTimeout(), TimeUnit.SECONDS);
  client.setConnectTimeout(connectorOptions.getConnectTimeout(), TimeUnit.SECONDS);
  client.setFollowRedirects(connectorOptions.isFollowRedirects());
  client.setFollowSslRedirects(connectorOptions.isFollowRedirects());
  client.setProxySelector(ProxySelector.getDefault());
  client.setCookieHandler(CookieHandler.getDefault());
  client.setCertificatePinner(CertificatePinner.DEFAULT);
  client.setAuthenticator(AuthenticatorAdapter.INSTANCE);
  client.setConnectionPool(ConnectionPool.getDefault());
  client.setProtocols(Util.immutableList(Protocol.HTTP_1_1));
  client.setConnectionSpecs(DEFAULT_CONNECTION_SPECS);
  client.setSocketFactory(SocketFactory.getDefault());
  Internal.instance.setNetwork(client, Network.DEFAULT);
  return client;
}

代码示例来源:origin: com.squareup.okhttp/mockwebserver

private void serveFile(FramedStream stream, File file) throws IOException {
 List<Header> responseHeaders = Arrays.asList(
   new Header(":status", "200"),
   new Header(":version", "HTTP/1.1"),
   new Header("content-type", contentType(file))
 );
 stream.reply(responseHeaders, true);
 Source source = Okio.source(file);
 try {
  BufferedSink out = Okio.buffer(stream.getSink());
  out.writeAll(source);
  out.close();
 } finally {
  Util.closeQuietly(source);
 }
}

代码示例来源:origin: liferay/liferay-mobile-sdk

public static void transfer(
    InputStream is, FileProgressCallback callback, Object tag,
    BufferedSink sink)
  throws IOException {
  Source source = null;
  try {
    source = Okio.source(is);
    Buffer os = new Buffer();
    while ((source.read(os, 2048) != -1) && !isCancelled(callback)) {
      byte[] bytes = os.readByteArray();
      if (sink != null) {
        sink.write(bytes);
      }
      if (callback != null) {
        callback.onBytes(bytes);
        callback.increment(bytes.length);
      }
    }
    if (isCancelled(callback)) {
      HttpUtil.cancel(tag);
    }
  }
  finally {
    Util.closeQuietly(source);
  }
}

相关文章