List of usage examples for org.apache.http.client.utils HttpClientUtils closeQuietly
public static void closeQuietly(final HttpClient httpClient)
From source file:com.hp.mqm.clt.RestClient.java
private void authenticate() throws IOException { HttpPost post = new HttpPost(createBaseUri(URI_AUTHENTICATION)); addClientTypeHeader(post, true);//from w w w .ja v a2 s .com String username = settings.getUser() != null ? settings.getUser() : ""; String password = settings.getPassword() != null ? settings.getPassword() : ""; String authorization = "{\"user\":\"" + username + "\",\"password\":\"" + password + "\"}"; StringEntity httpEntity = new StringEntity(authorization, ContentType.APPLICATION_JSON); post.setEntity(httpEntity); HttpResponse response = null; try { cookieStore.clear(); response = httpClient.execute(post); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new RuntimeException("Authentication failed: code=" + response.getStatusLine().getStatusCode() + "; reason=" + response.getStatusLine().getReasonPhrase()); } else { handleCookies(); } } finally { HttpClientUtils.closeQuietly(response); } }
From source file:org.alfresco.selenium.FetchUtil.java
/** * Retrieve file with authentication, using {@link WebDriver} cookie we * keep the session and use HttpClient to download files that requires * user to be authenticated. //from ww w .j a va2s .c om * @param resourceUrl path to file to download * @param driver {@link WebDriver} * @param output path to output the file * @throws IOException if error */ protected static File retrieveFile(final String resourceUrl, final CloseableHttpClient client, final File output) throws IOException { HttpGet httpGet = new HttpGet(resourceUrl); BufferedOutputStream bos = null; BufferedInputStream bis = null; HttpResponse response = null; try { response = client.execute(httpGet); HttpEntity entity = response.getEntity(); bos = new BufferedOutputStream(new FileOutputStream(output)); bis = new BufferedInputStream(entity.getContent()); int inByte; while ((inByte = bis.read()) != -1) bos.write(inByte); HttpClientUtils.closeQuietly(response); } catch (Exception e) { logger.error("Unable to fetch file " + resourceUrl, e); } finally { if (response != null) { HttpClientUtils.closeQuietly(response); } if (bis != null) { bis.close(); } if (bos != null) { bos.close(); } } return output; }
From source file:com.mirth.connect.client.core.ConnectServiceUtil.java
public static boolean sendStatistics(String serverId, String mirthVersion, boolean server, String data, String[] protocols, String[] cipherSuites) { if (data == null) { return false; }//from w w w . j a v a 2 s.c o m boolean isSent = false; CloseableHttpClient client = null; HttpPost post = new HttpPost(); CloseableHttpResponse response = null; NameValuePair[] params = { new BasicNameValuePair("serverId", serverId), new BasicNameValuePair("version", mirthVersion), new BasicNameValuePair("server", Boolean.toString(server)), new BasicNameValuePair("data", data) }; RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT) .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build(); post.setURI(URI.create(URL_CONNECT_SERVER + URL_USAGE_SERVLET)); post.setEntity(new UrlEncodedFormEntity(Arrays.asList(params), Charset.forName("UTF-8"))); try { HttpClientContext postContext = HttpClientContext.create(); postContext.setRequestConfig(requestConfig); client = getClient(protocols, cipherSuites); response = client.execute(post, postContext); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if ((statusCode == HttpStatus.SC_OK)) { isSent = true; } } catch (Exception e) { } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(client); } return isSent; }
From source file:com.hp.mqm.client.AbstractMqmRestClient.java
private void authenticate() { HttpPost post = new HttpPost(createBaseUri(URI_AUTHENTICATION)); StringEntity loginApiJson = new StringEntity("{\"user\":\"" + (username != null ? username : "") + "\"," + "\"password\":\"" + (password != null ? password : "") + "\"}", ContentType.APPLICATION_JSON); post.setHeader(HEADER_CLIENT_TYPE, clientType); post.setEntity(loginApiJson);/*from ww w . ja v a2s .co m*/ HttpResponse response = null; boolean tokenFound = false; try { cookieStore.clear(); response = httpClient.execute(post); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { for (Cookie cookie : cookieStore.getCookies()) { if (cookie.getName().equals(LWSSO_COOKIE_NAME)) { LWSSO_TOKEN = cookie; tokenFound = true; } } } else { throw new AuthenticationException( "Authentication failed: code=" + response.getStatusLine().getStatusCode() + "; reason=" + response.getStatusLine().getReasonPhrase()); } if (!tokenFound) { LWSSO_TOKEN = null; throw new AuthenticationException( "Authentication failed: status code was OK, but no security token found"); } } catch (IOException e) { throw new LoginErrorException("Error occurred during authentication", e); } finally { HttpClientUtils.closeQuietly(response); } }
From source file:sachin.spider.SpiderConfig.java
private String handleRedirect(String url) { try {/*from w ww. j av a 2s.c o m*/ HttpGet httpget = new HttpGet(url); RequestConfig requestConfig = RequestConfig.custom().setRedirectsEnabled(true) .setCircularRedirectsAllowed(true).setRelativeRedirectsAllowed(true) .setConnectionRequestTimeout(getConnectionRequestTimeout()).setSocketTimeout(getSocketTimeout()) .setConnectTimeout(getConnectionTimeout()).build(); httpget.setConfig(requestConfig); HttpClientBuilder builder = HttpClientBuilder.create(); builder.setUserAgent(getUserAgentString()); if (isAuthenticate()) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(getUsername(), getPassword())); builder.setDefaultCredentialsProvider(credentialsProvider); } CloseableHttpClient httpclient = builder.build(); HttpClientContext context = HttpClientContext.create(); CloseableHttpResponse response = httpclient.execute(httpget, context); HttpHost target = context.getTargetHost(); List<URI> redirectLocations = context.getRedirectLocations(); URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations); url = location.toString(); EntityUtils.consumeQuietly(response.getEntity()); HttpClientUtils.closeQuietly(response); } catch (IOException | URISyntaxException ex) { Logger.getLogger(SpiderConfig.class.getName()).log(Level.SEVERE, null, ex); System.err.println(url); } return url; }
From source file:sachin.spider.WebSpider.java
private void processURL(WebURL curUrl) { curUrl.setProccessed(true);// w ww .j a v a2s.c om String url = curUrl.getUrl(); HttpGet httpget = new HttpGet(url); RequestConfig requestConfig = getRequestConfigWithRedirectDisabled(); httpget.setConfig(requestConfig); try { HttpClientContext context = HttpClientContext.create(); long startingTime = System.currentTimeMillis(); try (CloseableHttpResponse response = httpclient.execute(httpget, context)) { long endingTime = System.currentTimeMillis(); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); curUrl.setStatusCode(statusCode); curUrl.setStatusMessage(EnglishReasonPhraseCatalog.INSTANCE.getReason(statusCode, Locale.ENGLISH)); curUrl.setResposneTime(((int) (endingTime - startingTime)) / 1000); curUrl.setHeaders(response.getAllHeaders()); curUrl.setBaseHref(context.getTargetHost().toString()); if (curUrl.getStatusCode() >= 300 && curUrl.getStatusCode() < 400) { handleRedirectedLink(curUrl); } else if (statusCode == 200) { try { processPage(response, curUrl); } catch (Exception ex) { Logger.getLogger(WebSpider.class.getName()).log(Level.SEVERE, null, ex); } } handleLink(curUrl, response, statusCode, EnglishReasonPhraseCatalog.INSTANCE.getReason(statusCode, Locale.ENGLISH)); EntityUtils.consumeQuietly(response.getEntity()); HttpClientUtils.closeQuietly(response); } } catch (Exception ex) { System.out.println(curUrl.getUrl()); curUrl.setErrorMsg(ex.toString()); Logger.getLogger(WebSpider.class.getName()).log(Level.SEVERE, null, ex); } finally { httpget.releaseConnection(); } }
From source file:com.mirth.connect.client.core.ServerConnection.java
/** * Allows multiple simultaneous requests. *//*from ww w .jav a 2 s.c om*/ private ClientResponse executeAsync(ClientRequest request) throws ClientException { HttpRequestBase requestBase = null; CloseableHttpResponse response = null; boolean shouldClose = true; try { requestBase = setupRequestBase(request, ExecuteType.ASYNC); response = client.execute(requestBase); ClientResponse responseContext = handleResponse(request, requestBase, response); if (responseContext.hasEntity()) { shouldClose = false; } return responseContext; } catch (Exception e) { if (requestBase != null && requestBase.isAborted()) { throw new RequestAbortedException(e); } else if (e instanceof ClientException) { throw (ClientException) e; } throw new ClientException(e); } finally { if (shouldClose) { HttpClientUtils.closeQuietly(response); } } }
From source file:org.sonatype.nexus.repository.proxy.ProxyFacetSupport.java
protected Content fetch(String url, Context context, @Nullable Content stale) throws IOException { HttpClient client = httpClient.getHttpClient(); checkState(config.remoteUrl.isAbsolute(), "Invalid remote URL '%s' for proxy repository %s, please fix your configuration", config.remoteUrl, getRepository().getName());/* w w w . ja va2s.c o m*/ URI uri; try { uri = config.remoteUrl.resolve(url); } catch (IllegalArgumentException e) { // NOSONAR log.warn("Unable to resolve url. Reason: {}", e.getMessage()); throw new BadRequestException("Invalid repository path"); } HttpRequestBase request = buildFetchHttpRequest(uri, context); if (stale != null) { final DateTime lastModified = stale.getAttributes().get(Content.CONTENT_LAST_MODIFIED, DateTime.class); if (lastModified != null) { request.addHeader(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified.toDate())); } final String etag = stale.getAttributes().get(Content.CONTENT_ETAG, String.class); if (etag != null) { request.addHeader(HttpHeaders.IF_NONE_MATCH, "\"" + etag + "\""); } } log.debug("Fetching: {}", request); HttpResponse response = execute(context, client, request); log.debug("Response: {}", response); StatusLine status = response.getStatusLine(); log.debug("Status: {}", status); final CacheInfo cacheInfo = getCacheController(context).current(); if (status.getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); log.debug("Entity: {}", entity); final Content result = createContent(context, response); result.getAttributes().set(Content.CONTENT_LAST_MODIFIED, extractLastModified(request, response)); result.getAttributes().set(Content.CONTENT_ETAG, extractETag(response)); result.getAttributes().set(CacheInfo.class, cacheInfo); return result; } try { if (status.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) { checkState(stale != null, "Received 304 without conditional GET (bad server?) from %s", uri); indicateVerified(context, stale, cacheInfo); } mayThrowProxyServiceException(response); } finally { HttpClientUtils.closeQuietly(response); } return null; }
From source file:com.hp.mqm.client.MqmRestClientImpl.java
@Override public List<String> getJobWorkspaceId(String ciServerId, String ciJobName) { HttpGet request = new HttpGet( createSharedSpaceInternalApiUri(URI_WORKSPACE_BY_JOB_AND_SERVER, ciServerId, ciJobName)); HttpResponse response = null;//from w w w . j ava 2s.c om try { response = execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_NO_CONTENT) { logger.info("Job " + ciJobName + " has no build context in Octane"); return new ArrayList<>(); } if (statusCode != HttpStatus.SC_OK) { throw createRequestException("workspace retrieval failed", response); } JSONArray workspaces = JSONArray .fromObject(IOUtils.toString(response.getEntity().getContent(), "UTF-8")); return workspaces.subList(0, workspaces.size()); } catch (IOException e) { throw new RequestErrorException("Cannot obtain status.", e); } finally { HttpClientUtils.closeQuietly(response); } }
From source file:com.hp.mqm.clt.RestClient.java
protected synchronized void logout() throws IOException { if (isLoggedIn) { HttpPost post = new HttpPost(createBaseUri(URI_LOGOUT)); addClientTypeHeader(post);/*from w ww . j av a 2 s . c o m*/ HttpResponse response = null; try { response = httpClient.execute(post); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK && response.getStatusLine().getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) { // required until defect #2919 is fixed throw new RuntimeException("Logout failed: code=" + response.getStatusLine().getStatusCode() + "; reason=" + response.getStatusLine().getReasonPhrase()); } isLoggedIn = false; } finally { HttpClientUtils.closeQuietly(response); } } }