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

The following examples show how to use org.apache.hc.client5.http.impl.classic.HttpClients. 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: Http5FileProvider.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Create an {@link HttpClientBuilder} object. Invoked by {@link #createHttpClient(Http5FileSystemConfigBuilder, GenericFileName, FileSystemOptions)}.
 *
 * @param builder Configuration options builder for HTTP4 provider
 * @param rootName The root path
 * @param fileSystemOptions The FileSystem options
 * @return an {@link HttpClientBuilder} object
 * @throws FileSystemException if an error occurs
 */
protected HttpClientBuilder createHttpClientBuilder(final Http5FileSystemConfigBuilder builder, final GenericFileName rootName,
        final FileSystemOptions fileSystemOptions) throws FileSystemException {
    final List<Header> defaultHeaders = new ArrayList<>();
    defaultHeaders.add(new BasicHeader(HttpHeaders.USER_AGENT, builder.getUserAgent(fileSystemOptions)));

    final ConnectionReuseStrategy connectionReuseStrategy = builder.isKeepAlive(fileSystemOptions)
            ? DefaultConnectionReuseStrategy.INSTANCE
            : (request, response, context) -> false;

    final HttpClientBuilder httpClientBuilder =
            HttpClients.custom()
            .setRoutePlanner(createHttpRoutePlanner(builder, fileSystemOptions))
            .setConnectionManager(createConnectionManager(builder, fileSystemOptions))
            .setConnectionReuseStrategy(connectionReuseStrategy)
            .setDefaultRequestConfig(createDefaultRequestConfig(builder, fileSystemOptions))
            .setDefaultHeaders(defaultHeaders)
            .setDefaultCookieStore(createDefaultCookieStore(builder, fileSystemOptions));

    if (!builder.getFollowRedirect(fileSystemOptions)) {
        httpClientBuilder.disableRedirectHandling();
    }

    return httpClientBuilder;
}
 
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: 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 #4
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 #5
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 #6
Source File: SpotifyHttpManager.java    From spotify-web-api-java with MIT License 4 votes vote down vote up
/**
 * Construct a new SpotifyHttpManager instance.
 *
 * @param builder The builder.
 */
public SpotifyHttpManager(Builder builder) {
  this.proxy = builder.proxy;
  this.proxyCredentials = builder.proxyCredentials;
  this.cacheMaxEntries = builder.cacheMaxEntries;
  this.cacheMaxObjectSize = builder.cacheMaxObjectSize;
  this.connectionRequestTimeout = builder.connectionRequestTimeout;
  this.connectTimeout = builder.connectTimeout;
  this.socketTimeout = builder.socketTimeout;

  CacheConfig cacheConfig = CacheConfig.custom()
    .setMaxCacheEntries(cacheMaxEntries != null ? cacheMaxEntries : DEFAULT_CACHE_MAX_ENTRIES)
    .setMaxObjectSize(cacheMaxObjectSize != null ? cacheMaxObjectSize : DEFAULT_CACHE_MAX_OBJECT_SIZE)
    .setSharedCache(false)
    .build();

  BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();

  if (proxy != null) {
    credentialsProvider.setCredentials(
      new AuthScope(null, proxy.getHostName(), proxy.getPort(), null, proxy.getSchemeName()),
      proxyCredentials
    );
  }

  RequestConfig requestConfig = RequestConfig
    .custom()
    .setCookieSpec(StandardCookieSpec.STRICT)
    .setProxy(proxy)
    .setConnectionRequestTimeout(builder.connectionRequestTimeout != null
      ? Timeout.ofMilliseconds(builder.connectionRequestTimeout)
      : RequestConfig.DEFAULT.getConnectionRequestTimeout())
    .setConnectTimeout(builder.connectTimeout != null
      ? Timeout.ofMilliseconds(builder.connectTimeout)
      : RequestConfig.DEFAULT.getConnectTimeout())
    .setResponseTimeout(builder.socketTimeout != null
      ? Timeout.ofMilliseconds(builder.socketTimeout)
      : RequestConfig.DEFAULT.getResponseTimeout())
    .build();

  this.httpClient = HttpClients
    .custom()
    .setDefaultCredentialsProvider(credentialsProvider)
    .setDefaultRequestConfig(requestConfig)
    .disableContentCompression()
    .build();

  this.httpClientCaching = CachingHttpClients
    .custom()
    .setCacheConfig(cacheConfig)
    .setDefaultCredentialsProvider(credentialsProvider)
    .setDefaultRequestConfig(requestConfig)
    .disableContentCompression()
    .build();
}