@Override
  public Response intercept(Chain chain) throws IOException {

    Request request = chain.request();

    long t1 = System.nanoTime();
    L.i(
        TAG,
        "Sending request="
            + request.url()
            + "   connection="
            + chain.connection()
            + "    head="
            + request.headers()
            + " request=");

    Response response = chain.proceed(request);
    long t2 = System.nanoTime();
    L.i(
        TAG,
        "Received response="
            + response.request().url()
            + "   connect time="
            + ((t2 - t1) / 1e6d)
            + "    head="
            + response.headers()
            + "    tostring"
            + response.toString());

    return response;
  }
  @Override
  public long open(DataSpec dataSpec) throws HttpDataSourceException {
    this.dataSpec = dataSpec;
    this.bytesRead = 0;
    this.bytesSkipped = 0;
    Request request = makeRequest(dataSpec);
    try {
      response = okHttpClient.newCall(request).execute();
      responseByteStream = response.body().byteStream();
    } catch (IOException e) {
      throw new HttpDataSourceException(
          "Unable to connect to " + dataSpec.uri.toString(), e, dataSpec);
    }

    int responseCode = response.code();

    // Check for a valid response code.
    if (!response.isSuccessful()) {
      Map<String, List<String>> headers = request.headers().toMultimap();
      closeConnectionQuietly();
      throw new InvalidResponseCodeException(responseCode, headers, dataSpec);
    }

    // Check for a valid content type.
    MediaType mediaType = response.body().contentType();
    String contentType = mediaType != null ? mediaType.toString() : null;
    if (contentTypePredicate != null && !contentTypePredicate.evaluate(contentType)) {
      closeConnectionQuietly();
      throw new InvalidContentTypeException(contentType, dataSpec);
    }

    // If we requested a range starting from a non-zero position and received a 200 rather than a
    // 206, then the server does not support partial requests. We'll need to manually skip to the
    // requested position.
    bytesToSkip = responseCode == 200 && dataSpec.position != 0 ? dataSpec.position : 0;

    // Determine the length of the data to be read, after skipping.
    long contentLength = response.body().contentLength();
    bytesToRead =
        dataSpec.length != C.LENGTH_UNBOUNDED
            ? dataSpec.length
            : contentLength != -1 ? contentLength - bytesToSkip : C.LENGTH_UNBOUNDED;

    opened = true;
    if (listener != null) {
      listener.onTransferStart();
    }

    return bytesToRead;
  }
Exemplo n.º 3
0
  @Override
  public Response intercept(Interceptor.Chain chain) throws IOException {
    Request request = chain.request();

    long t1 = System.nanoTime();
    Log.v(
        "CS_SDK",
        String.format(
            "Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers()));

    Response response = chain.proceed(request);

    long t2 = System.nanoTime();
    Log.v(
        "CS_SDK",
        String.format(
            "Received response for %s in %.1fms%n%s",
            response.request().url(), (t2 - t1) / 1e6d, response.headers()));

    return response;
  }
  @Override
  public T call() throws Exception {
    Request request = null;
    Response response = null;
    Exception exception = null;
    Call call = null;

    try {
      MNSLog.logD("[call] - ");

      if (context.getCancellationHandler().isCancelled()) {
        throw new InterruptedIOException("This task is cancelled!");
      }

      Request.Builder requestBuilder = new Request.Builder();

      // build request url
      String url = message.buildCanonicalURL();
      MNSUtils.signRequest(message);
      requestBuilder = requestBuilder.url(url);

      // set request headers
      for (String key : message.getHeaders().keySet()) {
        requestBuilder = requestBuilder.addHeader(key, message.getHeaders().get(key));
      }

      String contentType = message.getHeaders().get(MNSHeaders.CONTENT_TYPE);
      String content = message.getContent();

      // set request body
      if (message.getContent() != null) {
        MNSUtils.assertTrue(contentType != null, "Content type can't be null when send data!");
        requestBuilder =
            requestBuilder.method(
                message.getMethod().toString(),
                new ProgressTouchableRequestBody(
                    message.getContent().getBytes(), contentType, context.getProgressCallback()));
      } else {
        switch (message.getMethod()) {
          case PUT:
            requestBuilder =
                requestBuilder.method(
                    message.getMethod().toString(), RequestBody.create(null, new byte[0]));
            break;
          case GET:
            requestBuilder = requestBuilder.get();
            break;
          case HEAD:
            requestBuilder = requestBuilder.head();
            break;
          case DELETE:
            requestBuilder = requestBuilder.delete();
            break;
          default:
            break;
        }
      }

      request = requestBuilder.build();

      if (MNSLog.isEnableLog()) {
        MNSLog.logD("request url: " + request.url());
        Map<String, List<String>> headerMap = request.headers().toMultimap();
        for (String key : headerMap.keySet()) {
          MNSLog.logD("requestHeader " + key + ": " + headerMap.get(key).get(0));
        }
      }

      call = client.newCall(request);
      context.getCancellationHandler().setCall(call);

      // send request
      response = call.execute();

      if (MNSLog.isEnableLog()) {
        MNSLog.logD("response code: " + response.code() + " for url: " + request.url());
        Map<String, List<String>> headerMap = response.headers().toMultimap();
        for (String key : headerMap.keySet()) {
          MNSLog.logD("responseHeader " + key + ": " + headerMap.get(key).get(0));
        }
      }
    } catch (Exception e) {
      MNSLog.logE("Encounter local execpiton: " + e.toString());
      if (MNSLog.isEnableLog()) {
        e.printStackTrace();
      }
      exception = new ClientException(e.getMessage(), e);
    }

    if (exception == null && (response.code() == 203 || response.code() >= 300)) {
      try {
        exception = ResponseParsers.parseResponseErrorXML(response);
      } catch (IOException e) {
        exception = new ClientException(e.getMessage(), e);
      }
    } else if (exception == null) {
      try {
        T result = responseParser.parse(response);
        if (context.getCompletedCallback() != null) {
          context.getCompletedCallback().onSuccess(context.getRequest(), result);
        }
        return result;
      } catch (IOException e) {
        exception = new ClientException(e.getMessage(), e);
      }
    }

    // reconstruct exception caused by manually cancelling
    if ((call != null && call.isCanceled()) || context.getCancellationHandler().isCancelled()) {
      exception = new ClientException("Task is cancelled!", exception.getCause(), true);
    }

    if (exception instanceof ClientException) {
      if (context.getCompletedCallback() != null) {
        context
            .getCompletedCallback()
            .onFailure(context.getRequest(), (ClientException) exception, null);
      }
    } else {
      if (context.getCompletedCallback() != null) {
        context
            .getCompletedCallback()
            .onFailure(context.getRequest(), null, (ServiceException) exception);
      }
    }
    throw exception;
  }
 private boolean doesHaveUserAgent(Request request) {
   return request.headers().get(HEADER_USER_AGENT) != null;
 }