Esempio n. 1
0
  private static BufferedSource getBody(SmashRequest request) {
    if (request.getMethod() == GET || request.getMethod() == HEAD) {
      return null;
    }

    return request.getBody();
  }
Esempio n. 2
0
 private static RequestBody convertBody(SmashRequest request, BufferedSource body)
     throws SmashError {
   try {
     return RequestBody.create(MediaType.parse(request.getBodyContentType()), body.readUtf8());
   } catch (IOException ioe) {
     throw new SmashError(ioe);
   }
 }
Esempio n. 3
0
  public static @NonNull SmashNetworkData perform(SmashRequest<?> request) throws SmashError {
    SmashNetworkData data = new SmashNetworkData();

    try {
      Request.Builder okBuilder = new Request.Builder().url(request.getUrl());
      okBuilder.removeHeader("User-Agent").addHeader("User-Agent", Smash.getUserAgent());

      BufferedSource body = getBody(request);
      switch (request.getMethod()) {
        case GET:
          okBuilder = okBuilder.get();
          break;
        case POST:
          okBuilder = okBuilder.post(convertBody(request, body));
          break;
        case PUT:
          okBuilder = okBuilder.put(convertBody(request, body));
          break;
        case DELETE:
          okBuilder = okBuilder.delete(convertBody(request, body));
          break;
        case HEAD:
          okBuilder = okBuilder.head();
          break;
        case PATCH:
          okBuilder = okBuilder.patch(convertBody(request, body));
          break;
      }

      Request okRequest = okBuilder.build();
      Response okResponse = sHttpClient.newCall(okRequest).execute();

      if (body != null) {
        body.close();
      }

      data.code = okResponse.code();
      data.headers = okResponse.headers();
      data.source = okResponse.body().source();
      data.length = okResponse.body().contentLength();
    } catch (IOException ioe) {
      throw new SmashError(ioe);
    }

    return data;
  }