类com.squareup.okhttp.internal.Util源码实例Demo

下面列出了怎么用com.squareup.okhttp.internal.Util的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: sctalk   文件: GifLoadTask.java
private FilterInputStream getFromCache(String url) throws Exception {
    DiskLruCache cache = DiskLruCache.open(CommonUtil.getImageSavePath(), 1, 2, 2*1024*1024);
    cache.flush();
    String key = Util.hash(url);
    final DiskLruCache.Snapshot snapshot;
    try {
        snapshot = cache.get(key);
        if (snapshot == null) {
            return null;
        }
    } catch (IOException e) {
        return null;
    }
    FilterInputStream bodyIn = new FilterInputStream(snapshot.getInputStream(1)) {
        @Override
        public void close() throws IOException {
            snapshot.close();
            super.close();
        }
    };
    return bodyIn;
}
 
源代码2 项目: httplite   文件: MiscHandle.java
private String createBodyInfo(RecordedRequest request) {
    if(HttpUtil.getMimeType(request).equals("application/json")){
        Charset charset = HttpUtil.getChartset(request);
        String json = request.getBody().readString(charset);
        System.out.println("createBodyInfo:"+json);
        return String.format("JsonBody charSet:%s,body:%s",charset.displayName(),json);
    }else if(HttpUtil.getMimeType(request).equals("application/x-www-form-urlencoded")){
        System.out.println("FormBody");
        String s;
        StringBuilder sb = new StringBuilder();
        try {
            while ((s = request.getBody().readUtf8Line())!=null){
                sb.append(URLDecoder.decode(s, Util.UTF_8.name()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("createBodyInfo:"+sb.toString());
        return "FormBody:"+sb.toString();
    }else if(RecordedUpload.isMultipartContent(request)){
        return handleMultipart(request);
    }
    return HttpUtil.getMimeType(request);
}
 
源代码3 项目: bluemix-parking-meter   文件: HttpTransport.java
/**
 * Discards the response body so that the connection can be reused. This
 * needs to be done judiciously, since it delays the current request in
 * order to speed up a potential future request that may never occur.
 *
 * <p>A stream may be discarded to encourage response caching (a response
 * cannot be cached unless it is consumed completely) or to enable connection
 * reuse.
 */
private static boolean discardStream(HttpEngine httpEngine, InputStream responseBodyIn) {
  Connection connection = httpEngine.connection;
  if (connection == null) return false;
  Socket socket = connection.getSocket();
  if (socket == null) return false;
  try {
    int socketTimeout = socket.getSoTimeout();
    socket.setSoTimeout(DISCARD_STREAM_TIMEOUT_MILLIS);
    try {
      Util.skipAll(responseBodyIn);
      return true;
    } finally {
      socket.setSoTimeout(socketTimeout);
    }
  } catch (IOException e) {
    return false;
  }
}
 
源代码4 项目: bluemix-parking-meter   文件: Response.java
public final byte[] bytes() throws IOException {
  long contentLength = contentLength();
  if (contentLength > Integer.MAX_VALUE) {
    throw new IOException("Cannot buffer entire body for content length: " + contentLength);
  }

  if (contentLength != -1) {
    byte[] content = new byte[(int) contentLength];
    InputStream in = byteStream();
    Util.readFully(in, content);
    if (in.read() != -1) throw new IOException("Content-Length and stream length disagree");
    return content;

  } else {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Util.copy(byteStream(), out);
    return out.toByteArray();
  }
}
 
源代码5 项目: wildfly-samples   文件: HttpEngine.java
/**
 * Releases this engine so that its resources may be either reused or
 * closed. Also call {@link #automaticallyReleaseConnectionToPool} unless
 * the connection will be used to follow a redirect.
 */
public final void release(boolean streamCanceled) {
  // If the response body comes from the cache, close it.
  if (responseBodyIn == cachedResponseBody) {
    Util.closeQuietly(responseBodyIn);
  }

  if (!connectionReleased && connection != null) {
    connectionReleased = true;

    if (transport == null
        || !transport.makeReusable(streamCanceled, requestBodyOut, responseTransferIn)) {
      Util.closeQuietly(connection);
      connection = null;
    } else if (automaticallyReleaseConnectionToPool) {
      client.getConnectionPool().recycle(connection);
      connection = null;
    }
  }
}
 
源代码6 项目: IoTgo_Android_App   文件: Response.java
public final byte[] bytes() throws IOException {
  long contentLength = contentLength();
  if (contentLength > Integer.MAX_VALUE) {
    throw new IOException("Cannot buffer entire body for content length: " + contentLength);
  }

  if (contentLength != -1) {
    byte[] content = new byte[(int) contentLength];
    InputStream in = byteStream();
    Util.readFully(in, content);
    if (in.read() != -1) throw new IOException("Content-Length and stream length disagree");
    return content;

  } else {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Util.copy(byteStream(), out);
    return out.toByteArray();
  }
}
 
源代码7 项目: IoTgo_Android_App   文件: HttpTransport.java
/**
 * Discards the response body so that the connection can be reused. This
 * needs to be done judiciously, since it delays the current request in
 * order to speed up a potential future request that may never occur.
 *
 * <p>A stream may be discarded to encourage response caching (a response
 * cannot be cached unless it is consumed completely) or to enable connection
 * reuse.
 */
private static boolean discardStream(HttpEngine httpEngine, InputStream responseBodyIn) {
  Connection connection = httpEngine.connection;
  if (connection == null) return false;
  Socket socket = connection.getSocket();
  if (socket == null) return false;
  try {
    int socketTimeout = socket.getSoTimeout();
    socket.setSoTimeout(DISCARD_STREAM_TIMEOUT_MILLIS);
    try {
      Util.skipAll(responseBodyIn);
      return true;
    } finally {
      socket.setSoTimeout(socketTimeout);
    }
  } catch (IOException e) {
    return false;
  }
}
 
源代码8 项目: IoTgo_Android_App   文件: HttpTransport.java
private void readChunkSize() throws IOException {
  // read the suffix of the previous chunk
  if (bytesRemainingInChunk != NO_CHUNK_YET) {
    Util.readAsciiLine(in);
  }
  String chunkSizeString = Util.readAsciiLine(in);
  int index = chunkSizeString.indexOf(";");
  if (index != -1) {
    chunkSizeString = chunkSizeString.substring(0, index);
  }
  try {
    bytesRemainingInChunk = Integer.parseInt(chunkSizeString.trim(), 16);
  } catch (NumberFormatException e) {
    throw new ProtocolException("Expected a hex chunk size but was " + chunkSizeString);
  }
  if (bytesRemainingInChunk == 0) {
    hasMoreChunks = false;
    RawHeaders rawResponseHeaders = httpEngine.responseHeaders.getHeaders();
    RawHeaders.readHeaders(transport.socketIn, rawResponseHeaders);
    httpEngine.receiveHeaders(rawResponseHeaders);
    endOfInput();
  }
}
 
源代码9 项目: reader   文件: HttpEngine.java
/**
 * Releases this engine so that its resources may be either reused or
 * closed. Also call {@link #automaticallyReleaseConnectionToPool} unless
 * the connection will be used to follow a redirect.
 */
public final void release(boolean streamCanceled) {
  // If the response body comes from the cache, close it.
  if (responseBodyIn == cachedResponseBody) {
    Util.closeQuietly(responseBodyIn);
  }

  if (!connectionReleased && connection != null) {
    connectionReleased = true;

    if (transport == null
        || !transport.makeReusable(streamCanceled, requestBodyOut, responseTransferIn)) {
      Util.closeQuietly(connection);
      connection = null;
    } else if (automaticallyReleaseConnectionToPool) {
      client.getConnectionPool().recycle(connection);
      connection = null;
    }
  }
}
 
源代码10 项目: apiman   文件: HawkularMetricsClient.java
/**
 * 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);
}
 
源代码11 项目: android-discourse   文件: Response.java
public byte[] bytes() throws IOException {
    long contentLength = contentLength();
    if (contentLength > Integer.MAX_VALUE) {
        throw new IOException("Cannot buffer entire body for content length: " + contentLength);
    }

    if (contentLength != -1) {
        byte[] content = new byte[(int) contentLength];
        InputStream in = byteStream();
        Util.readFully(in, content);
        if (in.read() != -1)
            throw new IOException("Content-Length and stream length disagree");
        return content;

    } else {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Util.copy(byteStream(), out);
        return out.toByteArray();
    }
}
 
源代码12 项目: crosswalk-cordova-android   文件: ConnectionPool.java
/** Close and remove all connections in the pool. */
public void evictAll() {
  List<Connection> connections;
  synchronized (this) {
    connections = new ArrayList<Connection>(this.connections);
    this.connections.clear();
  }

  for (Connection connection : connections) {
    Util.closeQuietly(connection);
  }
}
 
源代码13 项目: cordova-android-chromeview   文件: RawHeaders.java
/** Reads headers or trailers into {@code out}. */
public static void readHeaders(InputStream in, RawHeaders out) throws IOException {
  // parse the result headers until the first blank line
  String line;
  while ((line = Util.readAsciiLine(in)).length() != 0) {
    out.addLine(line);
  }
}
 
源代码14 项目: L.TileLayer.Cordova   文件: ConnectionPool.java
/**
 * Gives {@code connection} to the pool. The pool may store the connection,
 * or close it, as its policy describes.
 *
 * <p>It is an error to use {@code connection} after calling this method.
 */
public void recycle(Connection connection) {
  if (connection.isSpdy()) {
    return;
  }

  if (!connection.isAlive()) {
    Util.closeQuietly(connection);
    return;
  }

  try {
    Platform.get().untagSocket(connection.getSocket());
  } catch (SocketException e) {
    // When unable to remove tagging, skip recycling and close.
    Platform.get().logW("Unable to untagSocket(): " + e);
    Util.closeQuietly(connection);
    return;
  }

  synchronized (this) {
    connections.addFirst(connection);
    connection.resetIdleStartTime();
  }

  executorService.submit(connectionsCleanupCallable);
}
 
@Override public final void disconnect() {
  // Calling disconnect() before a connection exists should have no effect.
  if (httpEngine != null) {
    // We close the response body here instead of in
    // HttpEngine.release because that is called when input
    // has been completely read from the underlying socket.
    // However the response body can be a GZIPInputStream that
    // still has unread data.
    if (httpEngine.hasResponse()) {
      Util.closeQuietly(httpEngine.getResponseBody());
    }
    httpEngine.release(true);
  }
}
 
源代码16 项目: wildfly-samples   文件: ConnectionPool.java
/** Returns a recycled connection to {@code address}, or null if no such connection exists. */
public synchronized Connection get(Address address) {
  Connection foundConnection = null;
  for (ListIterator<Connection> i = connections.listIterator(connections.size());
      i.hasPrevious(); ) {
    Connection connection = i.previous();
    if (!connection.getRoute().getAddress().equals(address)
        || !connection.isAlive()
        || System.nanoTime() - connection.getIdleStartTimeNs() >= keepAliveDurationNs) {
      continue;
    }
    i.remove();
    if (!connection.isSpdy()) {
      try {
        Platform.get().tagSocket(connection.getSocket());
      } catch (SocketException e) {
        Util.closeQuietly(connection);
        // When unable to tag, skip recycling and close
        Platform.get().logW("Unable to tagSocket(): " + e);
        continue;
      }
    }
    foundConnection = connection;
    break;
  }

  if (foundConnection != null && foundConnection.isSpdy()) {
    connections.addFirst(foundConnection); // Add it back after iteration.
  }

  executorService.submit(connectionsCleanupCallable);
  return foundConnection;
}
 
源代码17 项目: phonegapbootcampsite   文件: RawHeaders.java
/** Parses bytes of a response header from an HTTP transport. */
public static RawHeaders fromBytes(InputStream in) throws IOException {
  RawHeaders headers;
  do {
    headers = new RawHeaders();
    headers.setStatusLine(Util.readAsciiLine(in));
    readHeaders(in, headers);
  } while (headers.getResponseCode() == HttpEngine.HTTP_CONTINUE);
  return headers;
}
 
源代码18 项目: L.TileLayer.Cordova   文件: RawHeaders.java
/** Reads headers or trailers into {@code out}. */
public static void readHeaders(InputStream in, RawHeaders out) throws IOException {
  // parse the result headers until the first blank line
  String line;
  while ((line = Util.readAsciiLine(in)).length() != 0) {
    out.addLine(line);
  }
}
 
@Override public final Permission getPermission() throws IOException {
  String hostName = getURL().getHost();
  int hostPort = Util.getEffectivePort(getURL());
  if (usingProxy()) {
    InetSocketAddress proxyAddress = (InetSocketAddress) requestedProxy.address();
    hostName = proxyAddress.getHostName();
    hostPort = proxyAddress.getPort();
  }
  return new SocketPermission(hostName + ":" + hostPort, "connect, resolve");
}
 
源代码20 项目: cordova-amazon-fireos   文件: ConnectionPool.java
/**
 * Gives {@code connection} to the pool. The pool may store the connection,
 * or close it, as its policy describes.
 *
 * <p>It is an error to use {@code connection} after calling this method.
 */
public void recycle(Connection connection) {
  if (connection.isSpdy()) {
    return;
  }

  if (!connection.isAlive()) {
    Util.closeQuietly(connection);
    return;
  }

  try {
    Platform.get().untagSocket(connection.getSocket());
  } catch (SocketException e) {
    // When unable to remove tagging, skip recycling and close.
    Platform.get().logW("Unable to untagSocket(): " + e);
    Util.closeQuietly(connection);
    return;
  }

  synchronized (this) {
    connections.addFirst(connection);
    connection.resetIdleStartTime();
  }

  executorService.submit(connectionsCleanupCallable);
}
 
源代码21 项目: bluemix-parking-meter   文件: ConnectionPool.java
/** Close and remove all connections in the pool. */
public void evictAll() {
  List<Connection> connections;
  synchronized (this) {
    connections = new ArrayList<Connection>(this.connections);
    this.connections.clear();
  }

  for (Connection connection : connections) {
    Util.closeQuietly(connection);
  }
}
 
/** Returns a recycled connection to {@code address}, or null if no such connection exists. */
public synchronized Connection get(Address address) {
  Connection foundConnection = null;
  for (ListIterator<Connection> i = connections.listIterator(connections.size());
      i.hasPrevious(); ) {
    Connection connection = i.previous();
    if (!connection.getRoute().getAddress().equals(address)
        || !connection.isAlive()
        || System.nanoTime() - connection.getIdleStartTimeNs() >= keepAliveDurationNs) {
      continue;
    }
    i.remove();
    if (!connection.isSpdy()) {
      try {
        Platform.get().tagSocket(connection.getSocket());
      } catch (SocketException e) {
        Util.closeQuietly(connection);
        // When unable to tag, skip recycling and close
        Platform.get().logW("Unable to tagSocket(): " + e);
        continue;
      }
    }
    foundConnection = connection;
    break;
  }

  if (foundConnection != null && foundConnection.isSpdy()) {
    connections.addFirst(foundConnection); // Add it back after iteration.
  }

  executorService.submit(connectionsCleanupCallable);
  return foundConnection;
}
 
/**
 * Gives {@code connection} to the pool. The pool may store the connection,
 * or close it, as its policy describes.
 *
 * <p>It is an error to use {@code connection} after calling this method.
 */
public void recycle(Connection connection) {
  executorService.submit(connectionsCleanupCallable);

  if (connection.isSpdy()) {
    return;
  }

  if (!connection.isAlive()) {
    Util.closeQuietly(connection);
    return;
  }

  try {
    Platform.get().untagSocket(connection.getSocket());
  } catch (SocketException e) {
    // When unable to remove tagging, skip recycling and close.
    Platform.get().logW("Unable to untagSocket(): " + e);
    Util.closeQuietly(connection);
    return;
  }

  synchronized (this) {
    connections.addFirst(connection);
    connection.resetIdleStartTime();
  }
}
 
源代码24 项目: bluemix-parking-meter   文件: Http20Draft06.java
private void readGoAway(Handler handler, int flags, int length, int streamId)
    throws IOException {
  if (length < 8) throw ioException("TYPE_GOAWAY length < 8: %s", length);
  int lastStreamId = in.readInt();
  int errorCodeInt = in.readInt();
  int opaqueDataLength = length - 8;
  ErrorCode errorCode = ErrorCode.fromHttp2(errorCodeInt);
  if (errorCode == null) {
    throw ioException("TYPE_RST_STREAM unexpected error code: %d", errorCodeInt);
  }
  if (Util.skipByReading(in, opaqueDataLength) != opaqueDataLength) {
    throw new IOException("TYPE_GOAWAY opaque data was truncated");
  }
  handler.goAway(lastStreamId, errorCode);
}
 
源代码25 项目: L.TileLayer.Cordova   文件: SpdyConnection.java
@Override public void data(boolean inFinished, int streamId, InputStream in, int length)
    throws IOException {
  SpdyStream dataStream = getStream(streamId);
  if (dataStream == null) {
    writeSynResetLater(streamId, ErrorCode.INVALID_STREAM);
    Util.skipByReading(in, length);
    return;
  }
  dataStream.receiveData(in, length);
  if (inFinished) {
    dataStream.receiveFin();
  }
}
 
源代码26 项目: reader   文件: HttpURLConnectionImpl.java
@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");
}
 
源代码27 项目: cordova-amazon-fireos   文件: RawHeaders.java
/** Reads headers or trailers into {@code out}. */
public static void readHeaders(InputStream in, RawHeaders out) throws IOException {
  // parse the result headers until the first blank line
  String line;
  while ((line = Util.readAsciiLine(in)).length() != 0) {
    out.addLine(line);
  }
}
 
源代码28 项目: IoTgo_Android_App   文件: ConnectionPool.java
/**
 * Gives {@code connection} to the pool. The pool may store the connection,
 * or close it, as its policy describes.
 *
 * <p>It is an error to use {@code connection} after calling this method.
 */
public void recycle(Connection connection) {
  if (connection.isSpdy()) {
    return;
  }

  if (!connection.isAlive()) {
    Util.closeQuietly(connection);
    return;
  }

  try {
    Platform.get().untagSocket(connection.getSocket());
  } catch (SocketException e) {
    // When unable to remove tagging, skip recycling and close.
    Platform.get().logW("Unable to untagSocket(): " + e);
    Util.closeQuietly(connection);
    return;
  }

  synchronized (this) {
    connections.addFirst(connection);
    connection.resetIdleStartTime();
  }

  executorService.submit(connectionsCleanupCallable);
}
 
源代码29 项目: reader   文件: Http20Draft06.java
private void readGoAway(Handler handler, int flags, int length, int streamId)
    throws IOException {
  if (length < 8) throw ioException("TYPE_GOAWAY length < 8: %s", length);
  int lastStreamId = in.readInt();
  int errorCodeInt = in.readInt();
  int opaqueDataLength = length - 8;
  ErrorCode errorCode = ErrorCode.fromHttp2(errorCodeInt);
  if (errorCode == null) {
    throw ioException("TYPE_RST_STREAM unexpected error code: %d", errorCodeInt);
  }
  if (Util.skipByReading(in, opaqueDataLength) != opaqueDataLength) {
    throw new IOException("TYPE_GOAWAY opaque data was truncated");
  }
  handler.goAway(lastStreamId, errorCode);
}
 
源代码30 项目: reader   文件: ConnectionPool.java
/**
 * Gives {@code connection} to the pool. The pool may store the connection,
 * or close it, as its policy describes.
 *
 * <p>It is an error to use {@code connection} after calling this method.
 */
public void recycle(Connection connection) {
  if (connection.isSpdy()) {
    return;
  }

  if (!connection.isAlive()) {
    Util.closeQuietly(connection);
    return;
  }

  try {
    Platform.get().untagSocket(connection.getSocket());
  } catch (SocketException e) {
    // When unable to remove tagging, skip recycling and close.
    Platform.get().logW("Unable to untagSocket(): " + e);
    Util.closeQuietly(connection);
    return;
  }

  synchronized (this) {
    connections.addFirst(connection);
    connection.resetIdleStartTime();
  }

  executorService.submit(connectionsCleanupCallable);
}
 
 类所在包
 同包方法