List of usage examples for org.apache.http.impl.client CloseableHttpClient close
public void close() throws IOException;
From source file:gda.util.ElogEntry.java
/** * Post eLog Entry// w w w . j a va2 s.c om */ public void post() throws ELogEntryException { String entryType = "41";// entry type is always a log (41) String titleForPost = visit == null ? title : "Visit: " + visit + " - " + title; String content = buildContent(); MultipartEntityBuilder request = MultipartEntityBuilder.create().addTextBody("txtTITLE", titleForPost) .addTextBody("txtCONTENT", content).addTextBody("txtLOGBOOKID", logID) .addTextBody("txtGROUPID", groupID).addTextBody("txtENTRYTYPEID", entryType) .addTextBody("txtUSERID", userID); HttpEntity entity = request.build(); HttpPost httpPost = new HttpPost(targetPostURL); httpPost.setEntity(entity); CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; try { httpClient = HttpClients.createDefault(); response = httpClient.execute(httpPost); String responseString = EntityUtils.toString(response.getEntity()); System.out.println(responseString); if (!responseString.contains("New Log Entry ID")) { throw new ELogEntryException("Upload failed, status=" + response.getStatusLine().getStatusCode() + " response=" + responseString + " targetURL = " + targetPostURL + " titleForPost = " + titleForPost + " logID = " + logID + " groupID = " + groupID + " entryType = " + entryType + " userID = " + userID); } } catch (ELogEntryException e) { throw e; } catch (Exception e) { throw new ELogEntryException("Error in ELogger. Database:" + targetPostURL, e); } finally { try { if (httpClient != null) httpClient.close(); if (response != null) response.close(); } catch (IOException e) { elogger.error("Could not close connections", e); } } }
From source file:net.ymate.framework.commons.HttpClientHelper.java
public IHttpResponse post(String url, ContentType contentType, String content, Header[] headers, final String defaultResponseCharset) throws Exception { CloseableHttpClient _httpClient = __doBuildHttpClient(); try {// w w w . j a v a 2 s . co m RequestBuilder _reqBuilder = RequestBuilder.post().setUri(url).setEntity(EntityBuilder.create() .setContentEncoding(contentType == null || contentType.getCharset() == null ? DEFAULT_CHARSET : contentType.getCharset().name()) .setContentType(contentType).setText(content).build()); if (headers != null && headers.length > 0) { for (Header _header : headers) { _reqBuilder.addHeader(_header); } } return _httpClient.execute(_reqBuilder.build(), new ResponseHandler<IHttpResponse>() { public IHttpResponse handleResponse(HttpResponse response) throws IOException { if (StringUtils.isNotBlank(defaultResponseCharset)) { return new IHttpResponse.NEW(response, defaultResponseCharset); } return new IHttpResponse.NEW(response); } }); } finally { _httpClient.close(); } }
From source file:net.ymate.framework.commons.HttpClientHelper.java
public IHttpResponse post(String url, ContentType contentType, InputStream content, Header[] headers, final String defaultResponseCharset) throws Exception { CloseableHttpClient _httpClient = __doBuildHttpClient(); try {// w w w.j a v a2 s . c o m RequestBuilder _reqBuilder = RequestBuilder.post().setUri(url).setEntity(EntityBuilder.create() .setContentEncoding(contentType == null || contentType.getCharset() == null ? DEFAULT_CHARSET : contentType.getCharset().name()) .setContentType(contentType).setStream(content).build()); if (headers != null && headers.length > 0) { for (Header _header : headers) { _reqBuilder.addHeader(_header); } } return _httpClient.execute(_reqBuilder.build(), new ResponseHandler<IHttpResponse>() { public IHttpResponse handleResponse(HttpResponse response) throws IOException { if (StringUtils.isNotBlank(defaultResponseCharset)) { return new IHttpResponse.NEW(response, defaultResponseCharset); } return new IHttpResponse.NEW(response); } }); } finally { _httpClient.close(); } }
From source file:br.cefetrj.sagitarii.nunki.comm.WebClient.java
public String doGet(String action, String parameter) throws Exception { String result = "NO_ANSWER"; String mhpHost = gf.getHostURL(); String url = mhpHost + "/" + action + "?" + parameter; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); /*/* w w w. j a v a 2 s .c o m*/ if ( gf.useProxy() ) { if ( gf.getProxyInfo() != null ) { HttpHost httpproxy = new HttpHost( gf.getProxyInfo().getHost(), gf.getProxyInfo().getPort() ); httpClient.getCredentialsProvider().setCredentials( new AuthScope( gf.getProxyInfo().getHost(), gf.getProxyInfo().getPort() ), new UsernamePasswordCredentials( gf.getProxyInfo().getUser(), gf.getProxyInfo().getPassword() )); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, httpproxy); } } */ HttpGet getRequest = new HttpGet(url); getRequest.addHeader("accept", "application/json"); getRequest.addHeader("Content-Type", "plain/text; charset=utf-8"); getRequest.setHeader("User-Agent", "TaskManager Node"); HttpResponse response = httpClient.execute(getRequest); response.setHeader("Content-Type", "plain/text; charset=UTF-8"); int stCode = response.getStatusLine().getStatusCode(); if (stCode != 200) { // Error } else { HttpEntity entity = response.getEntity(); InputStreamReader isr = new InputStreamReader(entity.getContent(), "UTF-8"); result = convertStreamToString(isr); Charset.forName("UTF-8").encode(result); isr.close(); } httpClient.close(); return result; }
From source file:net.duckling.ddl.util.RESTClient.java
public JsonObject httpUpload(String url, String dataFieldName, byte[] data, List<NameValuePair> params) { CloseableHttpClient httpclient = HttpClients.createDefault(); try {//from w w w. j a va 2s . c o m HttpPost httppost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addBinaryBody(dataFieldName, data, ContentType.DEFAULT_BINARY, "tempfile"); for (NameValuePair hp : params) { builder.addPart(hp.getName(), new StringBody(hp.getValue(), ContentType.create("text/plain", Consts.UTF_8))); } HttpEntity reqEntity = builder.setCharset(CharsetUtils.get("UTF-8")).build(); httppost.setEntity(reqEntity); CloseableHttpResponse response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } try { BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(br); return je.getAsJsonObject(); } finally { response.close(); } } catch (IOException e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return null; }
From source file:org.jboss.pnc.mavenrepositorymanager.UploadOneThenDownloadAndVerifyArtifactHasOriginUrlTest.java
@Test public void extractBuildArtifacts_ContainsTwoUploads() throws Exception { // create a dummy non-chained build execution and repo session based on it BuildExecution execution = new TestBuildExecution(); RepositorySession rc = driver.createBuildRepository(execution, accessToken); assertThat(rc, notNullValue());/* www .java2s .c om*/ String baseUrl = rc.getConnectionInfo().getDeployUrl(); String path = "org/commonjava/indy/indy-core/0.17.0/indy-core-0.17.0.pom"; String content = "This is a test"; CloseableHttpClient client = HttpClientBuilder.create().build(); // upload a couple files related to a single GAV using the repo session deployment url // this simulates a build deploying one jar and its associated POM final String url = UrlUtils.buildUrl(baseUrl, path); assertThat("Failed to upload: " + url, ArtifactUploadUtils.put(client, url, content), equalTo(true)); // download the two files via the repo session's dependency URL, which will proxy the test http server // using the expectations above assertThat(download(UrlUtils.buildUrl(baseUrl, path)), equalTo(content)); ProjectVersionRef pvr = new SimpleProjectVersionRef("org.commonjava.indy", "indy-core", "0.17.0"); String artifactRef = new SimpleArtifactRef(pvr, "pom", null).toString(); // extract the "builtArtifacts" artifacts we uploaded above. RepositoryManagerResult repositoryManagerResult = rc.extractBuildArtifacts(); // check that both files are present in extracted result List<Artifact> builtArtifacts = repositoryManagerResult.getBuiltArtifacts(); log.info("Built artifacts: " + builtArtifacts.toString()); assertThat(builtArtifacts, notNullValue()); assertThat(builtArtifacts.size(), equalTo(1)); Artifact builtArtifact = builtArtifacts.get(0); assertThat(builtArtifact + " doesn't match pom ref: " + artifactRef, artifactRef.equals(builtArtifact.getIdentifier()), equalTo(true)); client.close(); }
From source file:com.dawg6.d3api.server.D3IO.java
protected Token requestToken() throws Exception { CloseableHttpClient client = HttpClientBuilder.create().build(); List<NameValuePair> params = new Vector<NameValuePair>(); params.add(new BasicNameValuePair("client_id", apiKey)); params.add(new BasicNameValuePair("client_secret", apiSecret)); params.add(new BasicNameValuePair("grant_type", "client_credentials")); HttpPost request = new HttpPost(TOKEN_SERVER_URL); request.setEntity(new UrlEncodedFormEntity(params)); HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() != 200) { log.log(Level.SEVERE, "HTTP Server Response: " + response.getStatusLine().getStatusCode()); throw new RuntimeException("HTTP Server Response: " + response.getStatusLine().getStatusCode()); }/*from w w w. ja v a2 s . co m*/ BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } client.close(); ObjectMapper mapper = new ObjectMapper(); mapper = mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); Token token = mapper.readValue(result.toString(), Token.class); if ((token != null) && (token.error != null)) throw new RuntimeException(token.error_description); return token; }
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; if (url.startsWith("http://")) { httpclient = HttpClients.createDefault(); } else {//from w w w . ja va 2 s .co m // 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.activiti.service.activiti.ProcessDefinitionService.java
protected BpmnModel executeRequestForXML(HttpUriRequest request, ServerConfig serverConfig, int expectedStatusCode) { ActivitiServiceException exception = null; CloseableHttpClient client = clientUtil.getHttpClient(serverConfig); try {/*from w ww . j a va 2 s . c om*/ CloseableHttpResponse response = client.execute(request); try { InputStream responseContent = response.getEntity().getContent(); XMLInputFactory xif = XMLInputFactory.newInstance(); InputStreamReader in = new InputStreamReader(responseContent, "UTF-8"); XMLStreamReader xtr = xif.createXMLStreamReader(in); BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr); boolean success = response.getStatusLine() != null && response.getStatusLine().getStatusCode() == expectedStatusCode; if (success) { return bpmnModel; } else { exception = new ActivitiServiceException( "An error occured while calling Activiti: " + response.getStatusLine()); } } catch (Exception e) { log.warn("Error consuming response from uri " + request.getURI(), e); exception = clientUtil.wrapException(e, request); } finally { response.close(); } } catch (Exception e) { log.error("Error executing request to uri " + request.getURI(), e); exception = clientUtil.wrapException(e, request); } finally { try { client.close(); } catch (Exception e) { log.warn("Error closing http client instance", e); } } if (exception != null) { throw exception; } return null; }
From source file:edu.lternet.pasta.common.audit.AuditManagerClient.java
/** * Logs an audit record with the Audit Manager. * Run in a separate thread./*from w w w . j a va2 s.c o m*/ */ public void run() { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); String url = this.urlHead; HttpPost httpPost = new HttpPost(url); BasicHttpContext localcontext = new BasicHttpContext(); httpPost.setHeader("Cookie", "auth-token=" + authToken.getTokenString()); try { logger.debug("Posting to Audit Manager at URL: " + url); // Set the request entity String xmlHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; String auditEntryXML = xmlHeader + auditRecord.toXML(); HttpEntity stringEntity = new StringEntity(auditEntryXML); httpPost.setEntity(stringEntity); HttpHost httpHost = new HttpHost(this.host, 8080, "http"); HttpResponse httpResponse = httpClient.execute(httpHost, httpPost, localcontext); int statusCode = httpResponse.getStatusLine().getStatusCode(); logger.debug("Response Code from Audit Manager: " + statusCode); HttpEntity httpEntity = httpResponse.getEntity(); String entityString = EntityUtils.toString(httpEntity); if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) { handleStatusCode(statusCode, entityString); } } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { logger.error(e.getMessage()); e.printStackTrace(); } } }