List of usage examples for org.apache.http.client.methods CloseableHttpResponse close
public void close() throws IOException;
From source file:be.samey.io.ServerConn.java
private void executeAppOnSever(String url, HttpEntity entity, Path archivePath) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); httppost = new HttpPost(url); httppost.setEntity(entity);// www.ja v a 2 s . c o m CloseableHttpResponse response = null; HttpEntity resEntity; try { response = httpclient.execute(httppost); resEntity = response.getEntity(); saveResponse(resEntity.getContent(), archivePath); EntityUtils.consume(resEntity); } finally { if (response != null) { response.close(); } } httpclient.close(); }
From source file:run.var.teamcity.cloud.docker.client.apcon.ApacheConnector.java
private static InputStream getInputStream(final CloseableHttpResponse response) throws IOException { final InputStream inputStream; // DK_CLD: do not forward the entity stream to Jersey if the connection has been upgraded. This prevent any // component of trying to reading it, which likely result in unexpected result or even deadlock. if (response.getEntity() == null) { inputStream = new ByteArrayInputStream(new byte[0]); } else {/*from w w w . j a va 2 s .co m*/ final InputStream i = response.getEntity().getContent(); if (i.markSupported()) { inputStream = i; } else { inputStream = new BufferedInputStream(i, ReaderWriter.BUFFER_SIZE); } } return new FilterInputStream(inputStream) { @Override public void close() throws IOException { response.close(); super.close(); } }; }
From source file:io.confluent.rest.SslTest.java
private int makeGetRequest(String url, String clientKeystoreLocation, String clientKeystorePassword, String clientKeyPassword) throws Exception { log.debug("Making GET " + url); HttpGet httpget = new HttpGet(url); CloseableHttpClient httpclient;//from w ww. j a v a 2 s. c o m if (url.startsWith("http://")) { httpclient = HttpClients.createDefault(); } else { // trust all self-signed certs. SSLContextBuilder sslContextBuilder = SSLContexts.custom() .loadTrustMaterial(new TrustSelfSignedStrategy()); // add the client keystore if it's configured. if (clientKeystoreLocation != null) { sslContextBuilder.loadKeyMaterial(new File(clientKeystoreLocation), clientKeystorePassword.toCharArray(), clientKeyPassword.toCharArray()); } SSLContext sslContext = sslContextBuilder.build(); SSLConnectionSocketFactory sslSf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); httpclient = HttpClients.custom().setSSLSocketFactory(sslSf).build(); } int statusCode = -1; CloseableHttpResponse response = null; try { response = httpclient.execute(httpget); statusCode = response.getStatusLine().getStatusCode(); } finally { if (response != null) { response.close(); } httpclient.close(); } return statusCode; }
From source file:com.hzq.car.CarTest.java
/** * ??post,json/*from w w w . j a v a 2 s. c o m*/ */ private String sendAndGetResponse(String url, List<NameValuePair> params) throws IOException { HttpPost post = new HttpPost(url); post.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); StringBuilder messageBuilder = new StringBuilder("\n"); messageBuilder.append(post.getMethod()); messageBuilder.append(" "); messageBuilder.append(post.getURI()); messageBuilder.append(" "); HttpEntity entity = post.getEntity(); String body = IOUtils.toString(entity.getContent()); List<NameValuePair> parse = URLEncodedUtils.parse(body, ContentType.get(entity).getCharset()); parse.stream().forEach(pair -> { messageBuilder.append(pair.getName()); messageBuilder.append(":"); messageBuilder.append(pair.getValue()); messageBuilder.append(" "); }); logger.warn("send httpRequest: {}", messageBuilder.toString()); CloseableHttpResponse response = client.execute(post); InputStream content = response.getEntity().getContent(); String s = IOUtils.toString(content); response.close(); logger.warn("get httpResponse: \n{}", s); return s; }
From source file:gr.uoc.nlp.opinion.analysis.suggestion.ElasticSearchIntegration.java
/** * * @param commentID/*from w ww . j a v a 2 s . c o m*/ * @param sentenceID */ public void removeFromElasticSearch(String commentID, String sentenceID) { CloseableHttpClient httpclient = HttpClients.createDefault(); String deleteURI = this.elasticSearchURI + commentID + "_" + sentenceID; System.out.println(deleteURI); // create DELETE REQUEST HttpDelete httpDelete = new HttpDelete(deleteURI); // send request CloseableHttpResponse response = null; try { response = httpclient.execute(httpDelete); } catch (IOException ex) { Logger.getLogger(ElasticSearchIntegration.class.getName()).log(Level.SEVERE, null, ex); } try { // close response (ideally inside a finally clause in a try/catch) response.close(); } catch (IOException ex) { Logger.getLogger(ElasticSearchIntegration.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.github.lpezet.antiope.bo.AdvancedAPIClient.java
@Override protected <T> Response<T> doInvoke(Request<?> pRequest, Unmarshaller<T, R> pUnmarshaller, HttpResponseHandler<APIServiceException> pErrorResponseHandler, ExecutionContext pExecutionContext) throws APIClientException, APIServiceException { HttpResponseHandler<APIWebServiceResponse<T>> oResponseHandler = createResponseHandler(pExecutionContext, pUnmarshaller);// w w w. jav a 2 s . c o m IMetrics oMetrics = pExecutionContext.getMetrics(); // Add service metrics. oMetrics.addProperty(APIRequestMetrics.ServiceName, pRequest.getServiceName()); oMetrics.addProperty(APIRequestMetrics.ServiceEndpoint, pRequest.getEndpoint()); // Apply whatever request options we know how to handle, such as user-agent. setUserAgent(pRequest); HttpRequestBase oHttpRequest = null; org.apache.http.HttpResponse oApacheResponse = null; try { if (mLogger.isDebugEnabled()) mLogger.debug("Sending Request: " + pRequest.toString()); HttpContext oHttpContext = HttpClientContext.create(); // NB: Signing should happen in createHttpRequest(). oHttpRequest = mHttpRequestFactory.createHttpRequest(pRequest, getAPIConfiguration(), oHttpContext, pExecutionContext); oMetrics.startEvent(APIRequestMetrics.HttpRequestTime); try { oApacheResponse = mHttpClient.execute(oHttpRequest, oHttpContext); } finally { oMetrics.endEvent(APIRequestMetrics.HttpRequestTime); } oMetrics.addProperty(APIRequestMetrics.StatusCode, oApacheResponse.getStatusLine().getStatusCode()); HttpResponse oHttpResponse = createResponse(oHttpRequest, pRequest, oApacheResponse); T oResponse = handleResponse(pRequest, oResponseHandler, oHttpRequest, oHttpResponse, oApacheResponse, pExecutionContext); return new Response<T>(oResponse, oHttpResponse); } catch (IOException ioe) { if (mLogger.isInfoEnabled()) mLogger.info("Unable to execute HTTP request: " + ioe.getMessage(), ioe); oMetrics.incrementCounter(APIRequestMetrics.Exception); oMetrics.addProperty(APIRequestMetrics.Exception, ioe.toString()); oMetrics.addProperty(APIRequestMetrics.APIRequestID, null); APIClientException ace = new APIClientException("Unable to execute HTTP request: " + ioe.getMessage(), ioe); // TODO /* * if (!shouldRetry(request.getOriginalRequest(), * httpRequest, * ace, * requestCount, * config.getRetryPolicy())) { * throw ace; * } */ // Cache the retryable exception // oRetriedException = ace; // resetRequestAfterError(pRequest, ioe); throw ace; } catch (RuntimeException e) { throw handleUnexpectedFailure(e, oMetrics); } catch (Error e) { throw handleUnexpectedFailure(e, oMetrics); } finally { /* * Some response handlers need to manually manage the HTTP * connection and will take care of releasing the connection on * their own, but if this response handler doesn't need the * connection left open, we go ahead and release the it to free * up resources. */ if (oResponseHandler != null && !oResponseHandler.needsConnectionLeftOpen()) { try { if (oApacheResponse != null) { if (oApacheResponse.getEntity() != null && oApacheResponse.getEntity().getContent() != null) { oApacheResponse.getEntity().getContent().close(); } if (oApacheResponse instanceof CloseableHttpResponse) { CloseableHttpResponse oCloseable = (CloseableHttpResponse) oApacheResponse; oCloseable.close(); } } } catch (IOException e) { mLogger.warn("Cannot close the response content.", e); } } } }
From source file:com.gsma.mobileconnect.utils.RestClient.java
/** * Make the specified request with the specified client context. * <p>/*from w w w . j av a 2s . com*/ * The specified cookies will be added to the request. A request will be aborted if it exceeds the specified timeout. * Non Json responses are converted and thrown as RestExceptions. * <p> * Ensures that all closable resources are closed. * * @param httpRequest The request to execute. * @param context The context to use when executing the request. * @param timeout The maximum time in milliseconds the request is allowed to take. * @param cookiesToProxy The cookies to add to the request. * @return The Rest response. * @throws RestException Thrown if the request exceeds the specified timeout, or a non Json response is received. * @throws IOException */ public RestResponse callRestEndPoint(HttpRequestBase httpRequest, HttpClientContext context, int timeout, List<KeyValuePair> cookiesToProxy) throws RestException, IOException { CookieStore cookieStore = buildCookieStore(httpRequest.getURI().getHost(), cookiesToProxy); CloseableHttpClient closeableHttpClient = getHttpClient(cookieStore); try { CloseableHttpResponse closeableHttpResponse = executeRequest(closeableHttpClient, httpRequest, context, timeout); try { RestResponse restResponse = buildRestResponse(httpRequest, closeableHttpResponse); checkRestResponse(restResponse); return restResponse; } finally { closeableHttpResponse.close(); } } finally { closeableHttpClient.close(); } }
From source file:org.wso2.carbon.ml.dataset.test.GetDatasetsTestCase.java
/** * Test retrieving all the available value-sets of a dataset. * @throws MLHttpClientException /*w w w.j av a2 s . c o m*/ * @throws IOException */ @Test(description = "Get dataset version from its ID", dependsOnMethods = "testGetVersionSetsOfdataset") public void testGetVersionSet() throws MLHttpClientException, IOException { CloseableHttpResponse response = mlHttpclient .doHttpGet("/api/datasets/versions/" + MLIntegrationTestConstants.VERSIONSET_ID); assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(), response.getStatusLine().getStatusCode()); response.close(); }
From source file:org.alfresco.cacheserver.http.CacheHttpClient.java
public void getNodeById(String hostname, int port, String username, String password, String nodeId, String nodeVersion, HttpCallback callback) throws IOException { HttpHost target = new HttpHost(hostname, port, "http"); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local // auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(target, basicAuth);/*from www .j a v a2 s . c o m*/ // Add AuthCache to the execution context HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); CloseableHttpClient httpClient = getHttpClient(target, localContext, username, password); try { RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000).setConnectTimeout(1000) .build(); String uri = "http://" + hostname + ":" + port + "/alfresco/api/-default-/private/alfresco/versions/1/contentByNodeId/" + nodeId + "/" + nodeVersion; HttpGet httpGet = new HttpGet(uri); httpGet.setHeader("Content-Type", "text/plain"); httpGet.setConfig(requestConfig); System.out.println("Executing request " + httpGet.getRequestLine()); CloseableHttpResponse response = httpClient.execute(target, httpGet, localContext); try { callback.execute(response.getEntity().getContent()); // EntityUtils.consume(response.getEntity()); } finally { response.close(); } } finally { httpClient.close(); } }