org.apache.hc.client5.http.impl.classic.CloseableHttpClient Java Examples

The following examples show how to use org.apache.hc.client5.http.impl.classic.CloseableHttpClient. 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: SpotifyHttpManager.java    From spotify-web-api-java with MIT License 5 votes vote down vote up
private CloseableHttpResponse execute(CloseableHttpClient httpClient, ClassicHttpRequest method) throws
  IOException {
  HttpCacheContext context = HttpCacheContext.create();
  CloseableHttpResponse response = httpClient.execute(method, context);

  try {
    CacheResponseStatus responseStatus = context.getCacheResponseStatus();

    if (responseStatus != null) {
      switch (responseStatus) {
        case CACHE_HIT:
          SpotifyApi.LOGGER.log(
            Level.CONFIG,
            "A response was generated from the cache with no requests sent upstream");
          break;
        case CACHE_MODULE_RESPONSE:
          SpotifyApi.LOGGER.log(
            Level.CONFIG,
            "The response was generated directly by the caching module");
          break;
        case CACHE_MISS:
          SpotifyApi.LOGGER.log(
            Level.CONFIG,
            "The response came from an upstream server");
          break;
        case VALIDATED:
          SpotifyApi.LOGGER.log(
            Level.CONFIG,
            "The response was generated from the cache after validating the entry with the origin server");
          break;
      }
    }
  } catch (Exception e) {
    SpotifyApi.LOGGER.log(Level.SEVERE, e.getMessage());
  }

  return response;
}
 
Example #5
Source File: Http5FileSystem.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
@Override
protected void doCloseCommunicationLink() {
    if (httpClient instanceof CloseableHttpClient) {
        try {
            ((CloseableHttpClient) httpClient).close();
        } catch (final IOException e) {
            throw new RuntimeException("Error closing HttpClient", e);
        }
    }
}
 
Example #6
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 #7
Source File: Hc5HttpServer.java    From wpcleaner with Apache License 2.0 2 votes vote down vote up
/**
 * Create an HttpServer object.
 * 
 * @param httpClient HTTP client.
 * @param baseUrl Base URL of the server.
 */
public Hc5HttpServer(CloseableHttpClient httpClient, String baseUrl) {
  this.httpClient = httpClient;
  this.baseUrl = baseUrl;
}
 
Example #8
Source File: Http5FileObject.java    From commons-vfs with Apache License 2.0 2 votes vote down vote up
/**
 * Execute the request using the given {@code httpRequest} and return a {@code ClassicHttpResponse} from the execution.
 *
 * @param httpRequest {@code HttpUriRequest} object
 * @return {@code ClassicHttpResponse} from the execution
 * @throws IOException if IO error occurs
 */
protected ClassicHttpResponse executeHttpUriRequest(final HttpUriRequest httpRequest) throws IOException {
    final CloseableHttpClient httpClient = (CloseableHttpClient) getAbstractFileSystem().getHttpClient();
    final HttpClientContext httpClientContext = getAbstractFileSystem().getHttpClientContext();
    return httpClient.execute(httpRequest, httpClientContext);
}