com.squareup.okhttp.internal.Util Java Examples

The following examples show how to use com.squareup.okhttp.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: HawkularMetricsClient.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #2
Source File: MiscHandle.java    From httplite with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #3
Source File: HttpEngine.java    From reader with MIT License 6 votes vote down vote up
/**
 * 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;
    }
  }
}
 
Example #4
Source File: HttpTransport.java    From IoTgo_Android_App with MIT License 6 votes vote down vote up
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();
  }
}
 
Example #5
Source File: HttpEngine.java    From wildfly-samples with MIT License 6 votes vote down vote up
/**
 * 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;
    }
  }
}
 
Example #6
Source File: HttpTransport.java    From bluemix-parking-meter with MIT License 6 votes vote down vote up
/**
 * 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;
  }
}
 
Example #7
Source File: Response.java    From bluemix-parking-meter with MIT License 6 votes vote down vote up
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();
  }
}
 
Example #8
Source File: Response.java    From IoTgo_Android_App with MIT License 6 votes vote down vote up
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();
  }
}
 
Example #9
Source File: HttpTransport.java    From IoTgo_Android_App with MIT License 6 votes vote down vote up
/**
 * 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;
  }
}
 
Example #10
Source File: GifLoadTask.java    From sctalk with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #11
Source File: Response.java    From android-discourse with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #12
Source File: Http20Draft06.java    From reader with MIT License 5 votes vote down vote up
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);
}
 
Example #13
Source File: Address.java    From reader with MIT License 5 votes vote down vote up
public Address(String uriHost, int uriPort, SSLSocketFactory sslSocketFactory,
    HostnameVerifier hostnameVerifier, OkAuthenticator authenticator, Proxy proxy,
    List<String> transports) throws UnknownHostException {
  if (uriHost == null) throw new NullPointerException("uriHost == null");
  if (uriPort <= 0) throw new IllegalArgumentException("uriPort <= 0: " + uriPort);
  if (authenticator == null) throw new IllegalArgumentException("authenticator == null");
  if (transports == null) throw new IllegalArgumentException("transports == null");
  this.proxy = proxy;
  this.uriHost = uriHost;
  this.uriPort = uriPort;
  this.sslSocketFactory = sslSocketFactory;
  this.hostnameVerifier = hostnameVerifier;
  this.authenticator = authenticator;
  this.transports = Util.immutableList(transports);
}
 
Example #14
Source File: HttpResponseCache.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
@Override public void abort() {
  synchronized (HttpResponseCache.this) {
    if (done) {
      return;
    }
    done = true;
    writeAbortCount++;
  }
  Util.closeQuietly(cacheOut);
  try {
    editor.abort();
  } catch (IOException ignored) {
  }
}
 
Example #15
Source File: ConnectionPool.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example #16
Source File: RawHeaders.java    From cordova-amazon-fireos with Apache License 2.0 5 votes vote down vote up
/** 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);
  }
}
 
Example #17
Source File: HttpURLConnectionImpl.java    From reader with MIT License 5 votes vote down vote up
@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");
}
 
Example #18
Source File: RawHeaders.java    From L.TileLayer.Cordova with MIT License 5 votes vote down vote up
/** 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);
  }
}
 
Example #19
Source File: HttpResponseCache.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
@Override
public void abort() {
    synchronized (HttpResponseCache.this) {
        if (done) {
            return;
        }
        done = true;
        writeAbortCount++;
    }
    Util.closeQuietly(cacheOut);
    try {
        editor.abort();
    } catch (IOException ignored) {
    }
}
 
Example #20
Source File: ConnectionPool.java    From reader with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example #21
Source File: ConnectionPool.java    From CordovaYoutubeVideoPlayer with MIT License 5 votes vote down vote up
/** 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;
}
 
Example #22
Source File: ConnectionPool.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #23
Source File: HttpResponseCache.java    From cordova-android-chromeview with Apache License 2.0 5 votes vote down vote up
@Override public void abort() {
  synchronized (HttpResponseCache.this) {
    if (done) {
      return;
    }
    done = true;
    writeAbortCount++;
  }
  Util.closeQuietly(cacheOut);
  try {
    editor.abort();
  } catch (IOException ignored) {
  }
}
 
Example #24
Source File: HttpURLConnectionImpl.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #25
Source File: RawHeaders.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #26
Source File: RawHeaders.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #27
Source File: HttpEngine.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
/**
 * Figures out what the response source will be, and opens a socket to that
 * source if necessary. Prepares the request headers and gets ready to start
 * writing the request body if it exists.
 */
public final void sendRequest() throws IOException {
    if (responseSource != null) {
        return;
    }

    prepareRawRequestHeaders();
    initResponseSource();
    OkResponseCache responseCache = client.getOkResponseCache();
    if (responseCache != null) {
        responseCache.trackResponse(responseSource);
    }

    // The raw response source may require the network, but the request
    // headers may forbid network use. In that case, dispose of the network
    // response and use a GATEWAY_TIMEOUT response instead, as specified
    // by http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.4.
    if (requestHeaders.isOnlyIfCached() && responseSource.requiresConnection()) {
        if (responseSource == ResponseSource.CONDITIONAL_CACHE) {
            Util.closeQuietly(cachedResponseBody);
        }
        this.responseSource = ResponseSource.CACHE;
        this.cacheResponse = GATEWAY_TIMEOUT_RESPONSE;
        RawHeaders rawResponseHeaders = RawHeaders.fromMultimap(cacheResponse.getHeaders(), true);
        setResponse(new ResponseHeaders(uri, rawResponseHeaders), cacheResponse.getBody());
    }

    if (responseSource.requiresConnection()) {
        sendSocketRequest();
    } else if (connection != null) {
        client.getConnectionPool().recycle(connection);
        connection = null;
    }
}
 
Example #28
Source File: SpdyConnection.java    From bluemix-parking-meter with MIT License 5 votes vote down vote up
@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();
  }
}
 
Example #29
Source File: ConnectionPool.java    From cordova-android-chromeview with Apache License 2.0 5 votes vote down vote up
/** 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);
  }
}
 
Example #30
Source File: HttpEngine.java    From crosswalk-cordova-android with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the source for this response. It may be corrected later if the
 * request headers forbids network use.
 */
private void initResponseSource() throws IOException {
  responseSource = ResponseSource.NETWORK;
  if (!policy.getUseCaches()) return;

  OkResponseCache responseCache = client.getOkResponseCache();
  if (responseCache == null) return;

  CacheResponse candidate = responseCache.get(
      uri, method, requestHeaders.getHeaders().toMultimap(false));
  if (candidate == null) return;

  Map<String, List<String>> responseHeadersMap = candidate.getHeaders();
  cachedResponseBody = candidate.getBody();
  if (!acceptCacheResponseType(candidate)
      || responseHeadersMap == null
      || cachedResponseBody == null) {
    Util.closeQuietly(cachedResponseBody);
    return;
  }

  RawHeaders rawResponseHeaders = RawHeaders.fromMultimap(responseHeadersMap, true);
  cachedResponseHeaders = new ResponseHeaders(uri, rawResponseHeaders);
  long now = System.currentTimeMillis();
  this.responseSource = cachedResponseHeaders.chooseResponseSource(now, requestHeaders);
  if (responseSource == ResponseSource.CACHE) {
    this.cacheResponse = candidate;
    setResponse(cachedResponseHeaders, cachedResponseBody);
  } else if (responseSource == ResponseSource.CONDITIONAL_CACHE) {
    this.cacheResponse = candidate;
  } else if (responseSource == ResponseSource.NETWORK) {
    Util.closeQuietly(cachedResponseBody);
  } else {
    throw new AssertionError();
  }
}