Example #1
0
 @Test
 public void simple() {
   Request request = fromArgs("http://example.com").createRequest();
   assertEquals("GET", request.method());
   assertEquals("http://example.com/", request.url().toString());
   assertNull(request.body());
 }
Example #2
0
 @Test
 public void put() throws IOException {
   Request request = fromArgs("-X", "PUT", "-d", "foo", "http://example.com").createRequest();
   assertEquals("PUT", request.method());
   assertEquals("http://example.com/", request.url().toString());
   assertEquals(3, request.body().contentLength());
 }
  @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;
  }
Example #4
0
 @Test
 public void headerSplitWithDate() {
   Request request =
       fromArgs("-H", "If-Modified-Since: Mon, 18 Aug 2014 15:16:06 GMT", "http://example.com")
           .createRequest();
   assertEquals("Mon, 18 Aug 2014 15:16:06 GMT", request.header("If-Modified-Since"));
 }
Example #5
0
 @Test
 public void userAgent() {
   Request request = fromArgs("-A", "foo", "http://example.com").createRequest();
   assertEquals("GET", request.method());
   assertEquals("http://example.com/", request.url().toString());
   assertEquals("foo", request.header("User-Agent"));
   assertNull(request.body());
 }
Example #6
0
 @Test
 public void dataPut() {
   Request request = fromArgs("-d", "foo", "-X", "PUT", "http://example.com").createRequest();
   RequestBody body = request.body();
   assertEquals("PUT", request.method());
   assertEquals("http://example.com/", request.url().toString());
   assertEquals("application/x-www-form-urlencoded; charset=utf-8", body.contentType().toString());
   assertEquals("foo", bodyAsString(body));
 }
Example #7
0
 @Test
 public void contentTypeHeader() {
   Request request =
       fromArgs("-d", "foo", "-H", "Content-Type: application/json", "http://example.com")
           .createRequest();
   RequestBody body = request.body();
   assertEquals("POST", request.method());
   assertEquals("http://example.com/", request.url().toString());
   assertEquals("application/json; charset=utf-8", body.contentType().toString());
   assertEquals("foo", bodyAsString(body));
 }
 @Override
 public Request authenticate(Route route, Response response) throws IOException {
   Request authenticated = innerAuthenticator.authenticate(route, response);
   if (authenticated != null) {
     String authorizationValue = authenticated.header("Authorization");
     if (authorizationValue != null && innerAuthenticator instanceof CachingAuthenticator) {
       authCache.put(authenticated.url().host(), (CachingAuthenticator) innerAuthenticator);
     }
   }
   return authenticated;
 }
 @Override
 public Response intercept(Chain chain) throws IOException {
   Request original = chain.request();
   Request request =
       chain
           .request()
           .newBuilder()
           .headers(computeHeaders())
           .method(original.method(), original.body())
           .build();
   return chain.proceed(request);
 }
 @Override
 public Response intercept(Interceptor.Chain chain) throws IOException {
   Request request = chain.request();
   request =
       (request
               .newBuilder()
               .header("X-Auth-Token", X_AUTH_TOKEN)
               .header("X-Response-Control", "minified"))
           .method(request.method(), request.body())
           .build();
   return chain.proceed(request);
 }
  @Override
  public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    Request request = realChain.request();
    StreamAllocation streamAllocation = realChain.streamAllocation();

    // We need the network to satisfy this request. Possibly for validating a conditional GET.
    boolean doExtensiveHealthChecks = !request.method().equals("GET");
    HttpStream httpStream = streamAllocation.newStream(client, doExtensiveHealthChecks);
    RealConnection connection = streamAllocation.connection();

    return realChain.proceed(request, streamAllocation, httpStream, connection);
  }
  @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;
  }
 @Override
 public Response intercept(Chain chain) throws IOException {
   Request request = chain.request();
   Request modifiedRequest =
       request
           .newBuilder()
           .addHeader(
               "Authorization",
               "Basic "
                   + Base64.getEncoder()
                       .encodeToString(
                           (credentials.getUsername() + ":" + credentials.getPassword())
                               .getBytes()))
           .build();
   return chain.proceed(modifiedRequest);
 }
  @Override
  public Response intercept(Chain chain) throws IOException {
    String paramValue;
    Request request = chain.request();

    if (location == "query") {
      String newQuery = request.url().uri().getQuery();
      paramValue = paramName + "=" + apiKey;
      if (newQuery == null) {
        newQuery = paramValue;
      } else {
        newQuery += "&" + paramValue;
      }

      URI newUri;
      try {
        newUri =
            new URI(
                request.url().uri().getScheme(),
                request.url().uri().getAuthority(),
                request.url().uri().getPath(),
                newQuery,
                request.url().uri().getFragment());
      } catch (URISyntaxException e) {
        throw new IOException(e);
      }

      request = request.newBuilder().url(newUri.toURL()).build();
    } else if (location == "header") {
      request = request.newBuilder().addHeader(paramName, apiKey).build();
    }
    return chain.proceed(request);
  }
  @Override
  public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    // Build new request
    Request.Builder builder = request.newBuilder();
    builder.header("Accept", "application/json");

    String token = oauthToken.get();
    if (Utils.isNotNullOrEmpty(token)) {
      setAuthHeader(builder, token);
    }

    request = builder.build();
    Response response = chain.proceed(request);

    // If response is Forbidden or Unauthorized, try to obtain a token via authorize() or via
    // config.
    if (response.code() != 401 && response.code() != 403) {
      return response;
    } else if (Utils.isNotNullOrEmpty(config.getUsername())
        && Utils.isNotNullOrEmpty(config.getPassword())) {
      synchronized (client) {
        token = authorize();
        if (token != null) {
          oauthToken.set(token);
        }
      }
    } else if (Utils.isNotNullOrEmpty(config.getOauthToken())) {
      token = config.getOauthToken();
      oauthToken.set(token);
    }

    // If token was obtain, then retry request using the obtained token.
    if (Utils.isNotNullOrEmpty(token)) {
      // Close the previous response to prevent leaked connections.
      response.body().close();

      setAuthHeader(builder, token);
      request = builder.build();
      return chain.proceed(request); // repeat request with new token
    } else {
      return response;
    }
  }
Example #16
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;
 }