示例#1
1
  /** Get events filtered by program orgUnit and between dates. */
  public static List<Event> getEvents(String program, String orgUnit, Date minDate, Date maxDate) {
    try {
      Response response;

      String DHIS_URL = PreferencesState.getInstance().getDhisURL();
      String startDate = EventExtended.format(minDate, EventExtended.AMERICAN_DATE_FORMAT);
      String endDate =
          EventExtended.format(
              new Date(maxDate.getTime() + (8 * 24 * 60 * 60 * 1000)),
              EventExtended.AMERICAN_DATE_FORMAT);
      String url =
          String.format(DHIS_URL + DHIS_CHECK_EVENT_API, program, orgUnit, startDate, endDate);
      Log.d(TAG, url);
      url = ServerAPIController.encodeBlanks(url);

      response = ServerAPIController.executeCall(null, url, "GET");
      if (!response.isSuccessful()) {
        Log.e(TAG, "pushData (" + response.code() + "): " + response.body().string());
        throw new IOException(response.message());
      }
      JSONObject events = new JSONObject(response.body().string());
      ObjectMapper mapper = new ObjectMapper();
      JsonNode jsonNode = mapper.convertValue(mapper.readTree(events.toString()), JsonNode.class);

      return EventsWrapper.getEvents(jsonNode);

    } catch (Exception ex) {
      ex.printStackTrace();
      return null;
    }
  }
 @Override
 public Response intercept(final Chain chain) throws IOException {
   long t1 = System.nanoTime();
   final Request request = chain.request();
   Log.v(
       NextClient.TAG,
       String.format(
           "[OkHttp Request] %s %s on %s%n", request.method(), request.url(), chain.connection()));
   if (mHeaders) {
     Log.v(NextClient.TAG, "[Request Headers] " + request.headers());
   }
   final Response response = chain.proceed(request);
   long t2 = System.nanoTime();
   Log.v(
       NextClient.TAG,
       String.format(
           "[OkHttp Response] %s %s (%s:%s) in %.1fms%n ",
           request.method(),
           request.url(),
           response.code(),
           response.message(),
           (t2 - t1) / 1e6d));
   if (mHeaders) {
     Log.v(NextClient.TAG, "[Response Headers] " + response.headers());
   }
   if (mBody) {
     Log.v(NextClient.TAG, "[OkHttp Response Body] " + responseToText(response));
   }
   return response;
 }
  @Override
  protected HttpResponse invoke(Request nativeRequest) throws IOException, InterruptedException {
    OkHttpClient requestScopedClient = globalClient.clone();
    requestScopedClient.setProxy(proxyForURI.apply(nativeRequest.uri()));

    Response response = requestScopedClient.newCall(nativeRequest).execute();

    HttpResponse.Builder<?> builder = HttpResponse.builder();
    builder.statusCode(response.code());
    builder.message(response.message());

    Builder<String, String> headerBuilder = ImmutableMultimap.builder();
    Headers responseHeaders = response.headers();
    for (String header : responseHeaders.names()) {
      headerBuilder.putAll(header, responseHeaders.values(header));
    }

    ImmutableMultimap<String, String> headers = headerBuilder.build();

    if (response.code() == 204 && response.body() != null) {
      response.body().close();
    } else {
      Payload payload = newInputStreamPayload(response.body().byteStream());
      contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers);
      builder.payload(payload);
    }

    builder.headers(filterOutContentHeaders(headers));

    return builder.build();
  }
示例#4
0
 public Entry(Response response) {
   this.url = response.request().urlString();
   this.varyHeaders = OkHeaders.varyHeaders(response);
   this.requestMethod = response.request().method();
   this.requestBody = response.request().body();
   this.protocol = response.protocol();
   this.code = response.code();
   this.message = response.message();
   this.responseHeaders = response.headers();
   this.handshake = response.handshake();
 }
 /**
  * Handle the given response, return the deserialized object when the response is successful.
  *
  * @param <T> Type
  * @param response Response
  * @param returnType Return type
  * @throws ApiException If the response has a unsuccessful status code or fail to deserialize the
  *     response body
  * @return Type
  */
 public <T> T handleResponse(Response response, Type returnType) throws ApiException {
   if (response.isSuccessful()) {
     if (returnType == null || response.code() == 204) {
       // returning null if the returnType is not defined,
       // or the status code is 204 (No Content)
       return null;
     } else {
       return deserialize(response, returnType);
     }
   } else {
     String respBody = null;
     if (response.body() != null) {
       try {
         respBody = response.body().string();
       } catch (IOException e) {
         throw new ApiException(
             response.message(), e, response.code(), response.headers().toMultimap());
       }
     }
     throw new ApiException(
         response.message(), response.code(), response.headers().toMultimap(), respBody);
   }
 }
  @Override
  public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
      throws IOException, AuthFailureError {
    OkHttpClient client = okHttpClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder =
        new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();

    for (final String name : headers.keySet()) {
      okHttpRequestBuilder.addHeader(name, headers.get(name));
    }

    for (final String name : additionalHeaders.keySet()) {
      okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus =
        new BasicStatusLine(
            parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(),
            okHttpResponse.message());

    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();

    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
      final String name = responseHeaders.name(i), value = responseHeaders.value(i);

      if (name != null) {
        response.addHeader(new BasicHeader(name, value));
      }
    }

    return response;
  }
示例#7
0
  private InputStream getInputStream(String urlStr) throws IOException {
    Request request = WallabagConnection.getRequest(WallabagConnection.getHttpURL(urlStr));

    Response response = WallabagConnection.getClient().newCall(request).execute();

    if (response.isSuccessful()) {
      return response.body().byteStream();
    } else {
      // TODO: fix
      throw new RuntimeException(
          String.format(
              App.getInstance().getString(R.string.unsuccessfulRequest_errorMessage),
              response.code(),
              response.message()));
    }
  }
示例#8
0
  @Override
  public Response load(@NonNull Uri uri, int networkPolicy) throws IOException {
    CacheControl cacheControl = null;
    if (networkPolicy != 0) {
      if (NetworkPolicy.isTimeoutOnly(networkPolicy)) {
        cacheControl = TIMEOUT;
      } else if (NetworkPolicy.isOfflineOnly(networkPolicy)) {
        cacheControl = CacheControl.FORCE_CACHE;
      } else {
        CacheControl.Builder builder = new CacheControl.Builder();
        if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) {
          builder.noCache();
        }
        if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) {
          builder.noStore();
        }
        cacheControl = builder.build();
      }
    }

    Request.Builder builder = new Request.Builder().url(uri.toString());
    if (cacheControl != null) {
      builder.cacheControl(cacheControl);
    }

    com.squareup.okhttp.Response response = client.newCall(builder.build()).execute();
    int responseCode = response.code();
    if (responseCode >= 300) {
      response.body().close();
      throw new ResponseException(
          responseCode + " " + response.message(), networkPolicy, responseCode);
    }

    boolean fromCache = response.cacheResponse() != null;

    ResponseBody responseBody = response.body();
    return new Response(responseBody.byteStream(), fromCache, responseBody.contentLength());
  }
  public Resources load(@Cache.Policy int policy) throws ExternalResourceException {
    buildUrl();

    Logger.i(ExternalResources.TAG, "Load configuration from url: " + url.build());

    final CacheControl cacheControl;
    switch (policy) {
      case Cache.POLICY_NONE:
        cacheControl = new CacheControl.Builder().noCache().noStore().build();
        break;
      case Cache.POLICY_OFFLINE:
        cacheControl = CacheControl.FORCE_CACHE;
        break;
      case Cache.POLICY_ALL:
      default:
        cacheControl = new CacheControl.Builder().build();
        break;
    }

    Logger.v(ExternalResources.TAG, "CachePolicy: " + policy);

    Request request = new Request.Builder().url(url.build()).cacheControl(cacheControl).build();

    try {
      Response response = client.newCall(request).execute();
      int responseCode = response.code();

      Logger.d(ExternalResources.TAG, "Response code: " + responseCode);
      if (responseCode >= 300) {
        response.body().close();
        throw new ResponseException(responseCode + " " + response.message(), policy, responseCode);
      }

      return converter.fromReader(response.body().charStream());
    } catch (IOException e) {
      throw new ExternalResourceException(e);
    }
  }
示例#10
0
  private static HttpResponse transformResponse(Response response) {
    int code = response.code();
    String message = response.message();
    BasicHttpResponse httpResponse = new BasicHttpResponse(HTTP_1_1, code, message);

    ResponseBody body = response.body();
    InputStreamEntity entity = new InputStreamEntity(body.byteStream(), body.contentLength());
    httpResponse.setEntity(entity);

    Headers headers = response.headers();
    for (int i = 0; i < headers.size(); i++) {
      String name = headers.name(i);
      String value = headers.value(i);
      httpResponse.addHeader(name, value);
      if ("Content-Type".equalsIgnoreCase(name)) {
        entity.setContentType(value);
      } else if ("Content-Encoding".equalsIgnoreCase(name)) {
        entity.setContentEncoding(value);
      }
    }

    return httpResponse;
  }
示例#11
0
  @Override
  public Response intercept(Chain chain) throws IOException {
    Level level = this.level;

    Request request = chain.request();
    if (level == Level.NONE) {
      return chain.proceed(request);
    }

    boolean logBody = level == Level.BODY;
    boolean logHeaders = logBody || level == Level.HEADERS;

    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;

    Connection connection = chain.connection();
    Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1;
    String requestStartMessage =
        "--> " + request.method() + ' ' + requestPath(request.httpUrl()) + ' ' + protocol(protocol);
    if (!logHeaders && hasRequestBody) {
      requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);

    if (logHeaders) {
      Headers headers = request.headers();
      for (int i = 0, count = headers.size(); i < count; i++) {
        logger.log(headers.name(i) + ": " + headers.value(i));
      }

      String endMessage = "--> END " + request.method();
      if (logBody && hasRequestBody) {
        Buffer buffer = new Buffer();
        requestBody.writeTo(buffer);

        Charset charset = UTF8;
        MediaType contentType = requestBody.contentType();
        if (contentType != null) {
          contentType.charset(UTF8);
        }

        logger.log("");
        logger.log(buffer.readString(charset));

        endMessage += " (" + requestBody.contentLength() + "-byte body)";
      }
      logger.log(endMessage);
    }

    long startNs = System.nanoTime();
    Response response = chain.proceed(request);
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

    ResponseBody responseBody = response.body();
    logger.log(
        "<-- "
            + protocol(response.protocol())
            + ' '
            + response.code()
            + ' '
            + response.message()
            + " ("
            + tookMs
            + "ms"
            + (!logHeaders ? ", " + responseBody.contentLength() + "-byte body" : "")
            + ')');

    if (logHeaders) {
      Headers headers = response.headers();
      for (int i = 0, count = headers.size(); i < count; i++) {
        logger.log(headers.name(i) + ": " + headers.value(i));
      }

      String endMessage = "<-- END HTTP";
      if (logBody) {
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();

        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
          charset = contentType.charset(UTF8);
        }

        if (responseBody.contentLength() != 0) {
          logger.log("");
          logger.log(buffer.clone().readString(charset));
        }

        endMessage += " (" + buffer.size() + "-byte body)";
      }
      logger.log(endMessage);
    }

    return response;
  }
示例#12
0
 @Override
 public String reasonPhrase() {
   return mResponse.message();
 }
示例#13
0
 public static StatusLine get(Response response) {
   return new StatusLine(response.protocol(), response.code(), response.message());
 }