org.apache.hc.core5.http.io.entity.EntityUtils Java Examples

The following examples show how to use org.apache.hc.core5.http.io.entity.EntityUtils. 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: HttpUtils.java    From drftpd with GNU General Public License v2.0 5 votes vote down vote up
public static String retrieveHttpAsString(String url) throws HttpException, IOException {
    RequestConfig requestConfig = RequestConfig.custom()
            .setResponseTimeout(5000, TimeUnit.MILLISECONDS)
            .setConnectTimeout(5000, TimeUnit.MILLISECONDS)
            .setConnectionRequestTimeout(5000, TimeUnit.MILLISECONDS)
            .setCookieSpec(StandardCookieSpec.IGNORE)
            .build();
    CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultRequestConfig(requestConfig)
            .setUserAgent(_userAgent)
            .build();
    HttpGet httpGet = new HttpGet(url);
    httpGet.setConfig(requestConfig);
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httpGet);
        final int statusCode = response.getCode();
        if (statusCode != HttpStatus.SC_OK) {
            throw new HttpException("Error " + statusCode + " for URL " + url);
        }
        HttpEntity entity = response.getEntity();
        String data = EntityUtils.toString(entity);
        EntityUtils.consume(entity);
        return data;
    } catch (IOException e) {
        throw new IOException("Error for URL " + url, e);
    } finally {
        if (response != null) {
            response.close();
        }
        httpclient.close();
    }
}
 
Example #2
Source File: HttpUtils.java    From drftpd with GNU General Public License v2.0 5 votes vote down vote up
public static String retrieveHttpAsString(String url) throws HttpException, IOException {
    RequestConfig requestConfig = RequestConfig.custom()
            .setResponseTimeout(5000, TimeUnit.MILLISECONDS)
            .setConnectTimeout(5000, TimeUnit.MILLISECONDS)
            .setConnectionRequestTimeout(5000, TimeUnit.MILLISECONDS)
            .setCookieSpec(StandardCookieSpec.IGNORE)
            .build();
    CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultRequestConfig(requestConfig)
            .setUserAgent(_userAgent)
            .build();
    HttpGet httpGet = new HttpGet(url);
    httpGet.setConfig(requestConfig);
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httpGet);
        final int statusCode = response.getCode();
        if (statusCode != HttpStatus.SC_OK) {
            throw new HttpException("Error " + statusCode + " for URL " + url);
        }
        HttpEntity entity = response.getEntity();
        String data = EntityUtils.toString(entity);
        EntityUtils.consume(entity);
        return data;
    } catch (IOException e) {
        throw new IOException("Error for URL " + url, e);
    } finally {
        if (response != null) {
            response.close();
        }
        httpclient.close();
    }
}
 
Example #3
Source File: StructurizrClient.java    From java with Apache License 2.0 5 votes vote down vote up
private boolean manageLockForWorkspace(long workspaceId, boolean lock) throws StructurizrClientException {
    if (workspaceId <= 0) {
        throw new IllegalArgumentException("The workspace ID must be a positive integer.");
    }

    try (CloseableHttpClient httpClient = HttpClients.createSystem()) {
        HttpUriRequestBase httpRequest;

        if (lock) {
            log.info("Locking workspace with ID " + workspaceId);
            httpRequest = new HttpPut(url + WORKSPACE_PATH + workspaceId + "/lock?user=" + getUser() + "&agent=" + agent);
        } else {
            log.info("Unlocking workspace with ID " + workspaceId);
            httpRequest = new HttpDelete(url + WORKSPACE_PATH + workspaceId + "/lock?user=" + getUser() + "&agent=" + agent);
        }

        addHeaders(httpRequest, "", "");
        debugRequest(httpRequest, null);

        try (CloseableHttpResponse response = httpClient.execute(httpRequest)) {
            debugResponse(response);

            String responseText = EntityUtils.toString(response.getEntity());
            ApiResponse apiResponse = ApiResponse.parse(responseText);
            log.info(responseText);

            if (response.getCode() == HttpStatus.SC_OK) {
                return apiResponse.isSuccess();
            } else {
                throw new StructurizrClientException(apiResponse.getMessage());
            }
        }
    } catch (Exception e) {
        log.error(e);
        throw new StructurizrClientException(e);
    }
}
 
Example #4
Source File: StructurizrClient.java    From java with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the workspace with the given ID.
 *
 * @param workspaceId the workspace ID
 * @return a Workspace instance
 * @throws StructurizrClientException   if there are problems related to the network, authorization, JSON deserialization, etc
 */
public Workspace getWorkspace(long workspaceId) throws StructurizrClientException {
    if (workspaceId <= 0) {
        throw new IllegalArgumentException("The workspace ID must be a positive integer.");
    }

    try (CloseableHttpClient httpClient = HttpClients.createSystem()) {
        log.info("Getting workspace with ID " + workspaceId);
        HttpGet httpGet = new HttpGet(url + WORKSPACE_PATH + workspaceId);
        addHeaders(httpGet, "", "");
        debugRequest(httpGet, null);

        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            debugResponse(response);

            String json = EntityUtils.toString(response.getEntity());
            if (response.getCode() == HttpStatus.SC_OK) {
                archiveWorkspace(workspaceId, json);

                if (encryptionStrategy == null) {
                    return new JsonReader().read(new StringReader(json));
                } else {
                    EncryptedWorkspace encryptedWorkspace = new EncryptedJsonReader().read(new StringReader(json));

                    if (encryptedWorkspace.getEncryptionStrategy() != null) {
                        encryptedWorkspace.getEncryptionStrategy().setPassphrase(encryptionStrategy.getPassphrase());
                        return encryptedWorkspace.getWorkspace();
                    } else {
                        // this workspace isn't encrypted, even though the client has an encryption strategy set
                        return new JsonReader().read(new StringReader(json));
                    }
                }
            } else {
                ApiResponse apiResponse = ApiResponse.parse(json);
                throw new StructurizrClientException(apiResponse.getMessage());
            }
        }
    } catch (Exception e) {
        log.error(e);
        throw new StructurizrClientException(e);
    }
}
 
Example #5
Source File: SpotifyHttpManager.java    From spotify-web-api-java with MIT License 4 votes vote down vote up
private String getResponseBody(CloseableHttpResponse httpResponse) throws
  IOException,
  SpotifyWebApiException,
  ParseException {

  final String responseBody = httpResponse.getEntity() != null
    ? EntityUtils.toString(httpResponse.getEntity(), "UTF-8")
    : null;
  String errorMessage = httpResponse.getReasonPhrase();

  if (responseBody != null && !responseBody.equals("")) {
    try {
      final JsonElement jsonElement = JsonParser.parseString(responseBody);

      if (jsonElement.isJsonObject()) {
        final JsonObject jsonObject = JsonParser.parseString(responseBody).getAsJsonObject();

        if (jsonObject.has("error")) {
          if (jsonObject.has("error_description")) {
            errorMessage = jsonObject.get("error_description").getAsString();
          } else if (jsonObject.get("error").isJsonObject() && jsonObject.getAsJsonObject("error").has("message")) {
            errorMessage = jsonObject.getAsJsonObject("error").get("message").getAsString();
          }
        }
      }
    } catch (JsonSyntaxException e) {
      // Not necessary
    }
  }

  switch (httpResponse.getCode()) {
    case HttpStatus.SC_BAD_REQUEST:
      throw new BadRequestException(errorMessage);
    case HttpStatus.SC_UNAUTHORIZED:
      throw new UnauthorizedException(errorMessage);
    case HttpStatus.SC_FORBIDDEN:
      throw new ForbiddenException(errorMessage);
    case HttpStatus.SC_NOT_FOUND:
      throw new NotFoundException(errorMessage);
    case 429: // TOO_MANY_REQUESTS (additional status code, RFC 6585)
      // Sets "Retry-After" header as described at https://beta.developer.spotify.com/documentation/web-api/#rate-limiting
      Header header = httpResponse.getFirstHeader("Retry-After");

      if (header != null) {
        throw new TooManyRequestsException(errorMessage, Integer.parseInt(header.getValue()));
      } else {
        throw new TooManyRequestsException(errorMessage);
      }
    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
      throw new InternalServerErrorException(errorMessage);
    case HttpStatus.SC_BAD_GATEWAY:
      throw new BadGatewayException(errorMessage);
    case HttpStatus.SC_SERVICE_UNAVAILABLE:
      throw new ServiceUnavailableException(errorMessage);
    default:
      return responseBody;
  }
}
 
Example #6
Source File: ApacheHttp5Client.java    From feign with Apache License 2.0 4 votes vote down vote up
Response.Body toFeignBody(ClassicHttpResponse httpResponse) {
  final HttpEntity entity = httpResponse.getEntity();
  if (entity == null) {
    return null;
  }
  return new Response.Body() {

    @Override
    public Integer length() {
      return entity.getContentLength() >= 0 && entity.getContentLength() <= Integer.MAX_VALUE
          ? (int) entity.getContentLength()
          : null;
    }

    @Override
    public boolean isRepeatable() {
      return entity.isRepeatable();
    }

    @Override
    public InputStream asInputStream() throws IOException {
      return entity.getContent();
    }

    @SuppressWarnings("deprecation")
    @Override
    public Reader asReader() throws IOException {
      return new InputStreamReader(asInputStream(), UTF_8);
    }

    @Override
    public Reader asReader(Charset charset) throws IOException {
      Util.checkNotNull(charset, "charset should not be null");
      return new InputStreamReader(asInputStream(), charset);
    }

    @Override
    public void close() throws IOException {
      EntityUtils.consume(entity);
    }
  };
}