org.apache.hc.client5.http.impl.classic.CloseableHttpResponse Java Examples
The following examples show how to use
org.apache.hc.client5.http.impl.classic.CloseableHttpResponse.
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: HttpClient.java From webdrivermanager with Apache License 2.0 | 6 votes |
public CloseableHttpResponse execute(ClassicHttpRequest method) throws IOException { CloseableHttpResponse response = closeableHttpClient.execute(method); int responseCode = response.getCode(); if (responseCode >= SC_BAD_REQUEST) { String errorMessage; String methodUri = ""; try { methodUri = method.getUri().toString(); } catch (Exception e) { log.trace("Exception reading URI from method: {}", e.getMessage()); } errorMessage = "Error HTTP " + responseCode + " executing " + methodUri; log.error(errorMessage); throw new WebDriverManagerException(errorMessage); } return response; }
Example #2
Source File: HttpUtils.java From drftpd with GNU General Public License v2.0 | 5 votes |
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: WebDriverManager.java From webdrivermanager with Apache License 2.0 | 5 votes |
/** * This method works also for http://npm.taobao.org/ and * https://bitbucket.org/ mirrors. */ protected List<URL> getDriversFromMirror(URL driverUrl) throws IOException { if (!mirrorLog) { log.debug("Crawling driver list from mirror {}", driverUrl); mirrorLog = true; } else { log.trace("[Recursive call] Crawling driver list from mirror {}", driverUrl); } String driverStr = driverUrl.toString(); String driverOrigin = String.format("%s://%s", driverUrl.getProtocol(), driverUrl.getAuthority()); try (CloseableHttpResponse response = httpClient .execute(httpClient.createHttpGet(driverUrl))) { InputStream in = response.getEntity().getContent(); org.jsoup.nodes.Document doc = Jsoup.parse(in, null, driverStr); Iterator<org.jsoup.nodes.Element> iterator = doc.select("a") .iterator(); List<URL> urlList = new ArrayList<>(); while (iterator.hasNext()) { String link = iterator.next().attr("abs:href"); if (link.startsWith(driverStr) && link.endsWith(SLASH)) { urlList.addAll(getDriversFromMirror(new URL(link))); } else if (link.startsWith(driverOrigin) && !link.contains("icons") && (link.toLowerCase().endsWith(".bz2") || link.toLowerCase().endsWith(".zip") || link.toLowerCase().endsWith(".gz"))) { urlList.add(new URL(link)); } } return urlList; } }
Example #4
Source File: HttpUtils.java From drftpd with GNU General Public License v2.0 | 5 votes |
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 #5
Source File: StructurizrClient.java From java with Apache License 2.0 | 5 votes |
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 #6
Source File: SpotifyHttpManager.java From spotify-web-api-java with MIT License | 5 votes |
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 #7
Source File: ApacheDockerHttpClientImpl.java From docker-java with Apache License 2.0 | 5 votes |
@Override public Response execute(Request request) { HttpContext context = new BasicHttpContext(); HttpUriRequestBase httpUriRequest = new HttpUriRequestBase(request.method(), URI.create(request.path())); httpUriRequest.setScheme(host.getSchemeName()); httpUriRequest.setAuthority(new URIAuthority(host.getHostName(), host.getPort())); request.headers().forEach(httpUriRequest::addHeader); InputStream body = request.body(); if (body != null) { httpUriRequest.setEntity(new InputStreamEntity(body, null)); } if (request.hijackedInput() != null) { context.setAttribute(HijackingHttpRequestExecutor.HIJACKED_INPUT_ATTRIBUTE, request.hijackedInput()); httpUriRequest.setHeader("Upgrade", "tcp"); httpUriRequest.setHeader("Connection", "Upgrade"); } try { CloseableHttpResponse response = httpClient.execute(host, httpUriRequest, context); return new ApacheResponse(httpUriRequest, response); } catch (IOException e) { throw new RuntimeException(e); } }
Example #8
Source File: StructurizrClient.java From java with Apache License 2.0 | 4 votes |
/** * 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 #9
Source File: StructurizrClient.java From java with Apache License 2.0 | 4 votes |
private void debugResponse(CloseableHttpResponse response) { log.debug(response.getCode()); }
Example #10
Source File: SpotifyHttpManager.java From spotify-web-api-java with MIT License | 4 votes |
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 #11
Source File: ApacheDockerHttpClientImpl.java From docker-java with Apache License 2.0 | 4 votes |
ApacheResponse(HttpUriRequestBase httpUriRequest, CloseableHttpResponse response) { this.request = httpUriRequest; this.response = response; }