List of usage examples for org.apache.http.impl.client CloseableHttpClient close
public void close() throws IOException;
From source file:net.ymate.platform.module.wechat.support.HttpClientHelper.java
public String doGet(String url) throws Exception { CloseableHttpClient _httpClient = __doBuildHttpClient(); try {/*w w w .ja va 2 s . c o m*/ _LOG.debug("Request URL [" + url + "]"); String _result = _httpClient.execute(RequestBuilder.get().setUri(url).build(), new ResponseHandler<String>() { public String handleResponse(HttpResponse response) throws IOException { return EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET); } }); _LOG.debug("Request URL [" + url + "] Response [" + _result + "]"); return _result; } finally { _httpClient.close(); } }
From source file:Onlinedata.MainSendRequest.java
public void uploadData(String filename, String toBeUploaded) { upload = filename + ";" + toBeUploaded; uploadurl = baseurl;/* w ww. ja va 2 s . c om*/ try { CloseableHttpClient httpclient = HttpClients.createDefault(); StringEntity cliententity = new StringEntity(upload, ContentType.create("plain/text", Consts.UTF_8)); HttpPost httppost = new HttpPost(uploadurl); httppost.setEntity(cliententity); CloseableHttpResponse response = httpclient.execute(httppost); try { HttpEntity serverentity = response.getEntity(); if (serverentity != null) { long len = serverentity.getContentLength(); if (len != -1 && len < 2048) { System.out.println(EntityUtils.toString(serverentity)); } else { // Stream content out } } } catch (IOException | ParseException ex) { Logger.getLogger(MainSendRequest.class.getName()).log(Level.SEVERE, null, ex); } finally { response.close(); } httpclient.close(); } catch (IOException ex) { Logger.getLogger(MainSendRequest.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.flowable.ui.modeler.service.AppDefinitionPublishService.java
protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey, String deploymentName) {/*from w w w . ja v a 2 s . c om*/ String deployApiUrl = modelerAppProperties.getDeploymentApiUrl(); Assert.hasText(deployApiUrl, "flowable.modeler.app.deployment-api-url must be set"); String basicAuthUser = properties.getIdmAdmin().getUser(); String basicAuthPassword = properties.getIdmAdmin().getPassword(); String tenantId = tenantProvider.getTenantId(); if (!deployApiUrl.endsWith("/")) { deployApiUrl = deployApiUrl.concat("/"); } deployApiUrl = deployApiUrl .concat(String.format("app-repository/deployments?deploymentKey=%s&deploymentName=%s", encode(deploymentKey), encode(deploymentName))); if (tenantId != null) { StringBuilder sb = new StringBuilder(deployApiUrl); sb.append("&tenantId=").append(encode(tenantId)); deployApiUrl = sb.toString(); } HttpPost httpPost = new HttpPost(deployApiUrl); httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.getEncoder() .encode((basicAuthUser + ":" + basicAuthPassword).getBytes(Charset.forName("UTF-8"))))); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); entityBuilder.addBinaryBody("artifact", zipArtifact, ContentType.DEFAULT_BINARY, artifactName); HttpEntity entity = entityBuilder.build(); httpPost.setEntity(entity); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); clientBuilder .setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } })); } catch (Exception e) { LOGGER.error("Could not configure SSL for http client", e); throw new InternalServerErrorException("Could not configure SSL for http client", e); } CloseableHttpClient client = clientBuilder.build(); try { HttpResponse response = client.execute(httpPost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) { return; } else { LOGGER.error("Invalid deploy result code: {} for url", response.getStatusLine() + httpPost.getURI().toString()); throw new InternalServerErrorException("Invalid deploy result code: " + response.getStatusLine()); } } catch (IOException ioe) { LOGGER.error("Error calling deploy endpoint", ioe); throw new InternalServerErrorException("Error calling deploy endpoint: " + ioe.getMessage()); } finally { if (client != null) { try { client.close(); } catch (IOException e) { LOGGER.warn("Exception while closing http client", e); } } } }
From source file:edu.harvard.hul.ois.drs.pdfaconvert.clients.HttpClientIntegrationTest.java
@Test public void noFileParameterValueTest() throws URISyntaxException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL fileUrl = loader.getResource(INPUT_FILENAME); File inputFile = new File(fileUrl.toURI()); assertNotNull(inputFile);//from w ww.j a v a 2s . co m assertTrue(inputFile.exists()); assertTrue(inputFile.isFile()); assertTrue(inputFile.canRead()); CloseableHttpClient httpclient = HttpClients.createDefault(); String url = LOCAL_TOMCAT_SERVICE_URL + "?file="; HttpGet httpGet = new HttpGet(url); CloseableHttpResponse response = null; try { logger.debug("executing request " + httpGet.getRequestLine()); response = httpclient.execute(httpGet); StatusLine statusLine = response.getStatusLine(); logger.debug("Response status line : " + statusLine); assertEquals(400, statusLine.getStatusCode()); } catch (IOException e) { logger.error("Something went wrong...", e); fail(e.getMessage()); } finally { if (response != null) { try { response.close(); httpclient.close(); } catch (IOException e) { // nothing to do ; } } } logger.debug("DONE"); }
From source file:com.portfolio.data.utils.PostForm.java
public static boolean sendFile(String sessionid, String backend, String user, String uuid, String lang, File file) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try {// w w w . j a va2s.co m // Server + "/resources/resource/file/" + uuid +"?lang="+ lang // "http://"+backend+"/user/"+user+"/file/"+uuid+"/"+lang+"ptype/fs"; String url = "http://" + backend + "/resources/resource/file/" + uuid + "?lang=" + lang; HttpPost post = new HttpPost(url); post.setHeader("Cookie", "JSESSIONID=" + sessionid); // So that the receiving servlet allow us /// Remove import language tag String filename = file.getName(); /// NOTE: Since it's used with zip import, specific code. int langindex = filename.lastIndexOf("_"); filename = filename.substring(0, langindex) + filename.substring(langindex + 3); FileBody bin = new FileBody(file, ContentType.DEFAULT_BINARY, filename); // File from import /// Form info HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("uploadfile", bin).build(); post.setEntity(reqEntity); CloseableHttpResponse response = httpclient.execute(post); /* try { HttpEntity resEntity = response.getEntity(); /// Will be JSON if( resEntity != null ) { BufferedReader reader = new BufferedReader(new InputStreamReader(resEntity.getContent(), "UTF-8")); StringBuilder builder = new StringBuilder(); for( String line = null; (line = reader.readLine()) != null; ) builder.append(line).append("\n"); updateResource( sessionid, backend, uuid, lang, builder.toString() ); } EntityUtils.consume(resEntity); } finally { response.close(); } //*/ } finally { httpclient.close(); } return true; }
From source file:shootersubdownloader.Shootersubdownloader.java
private static void down(File f) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); String url = String.format("https://www.shooter.cn/api/subapi.php?filehash=%s&pathinfo=%s&format=json", computefilehash(f), f.getName()); System.out.println(url);/*from ww w . j av a2 s .c om*/ HttpGet request = new HttpGet(url); CloseableHttpResponse r = httpclient.execute(request); System.out.println(r.getStatusLine()); HttpEntity e = r.getEntity(); String s = EntityUtils.toString(e); System.out.println(s); JSONArray json = JSONArray.fromObject(s); // JSONObject json = JSONObject.fromObject(s); System.out.println(json.size()); for (int i = 0; i < json.size(); i++) { System.out.println(i); JSONObject obj = json.getJSONObject(i); JSONArray fs = obj.getJSONArray("Files"); String downurl = fs.getJSONObject(0).getString("Link"); HttpGet r2 = new HttpGet(downurl); CloseableHttpResponse res2 = httpclient.execute(r2); // Header[] headers = res2.getAllHeaders(); // for(Header h:headers){ // System.out.println(h.getName()); // System.out.println(h.getValue()); // } Header header = res2.getFirstHeader("Content-Disposition"); String sig = "filename="; String v = header.getValue(); String fn = v.substring(v.indexOf(sig) + sig.length()); HttpEntity e2 = res2.getEntity(); File outf = new File(fn); FileOutputStream fos = new FileOutputStream(outf); e2.writeTo(fos); System.out.println(filecharsetdetect.FileCharsetDetect.detect(outf)); // res2.getEntity().writeTo(new FileOutputStream(fn)); System.out.println(fn); res2.close(); } r.close(); httpclient.close(); }
From source file:com.fpmislata.banco.business.service.impl.PeticionRetirarDineroServiceImpl.java
@Override public void sendPeticionBancaria(CredencialesBancarias credencialesBancarias, String cccOrigen, String concepto, BigDecimal importe, String codigoEntidadBancaria) throws BusinessException { CloseableHttpClient httpClient = HttpClients.createDefault(); try {/*from w ww . j a v a 2s.c o m*/ Extraccion extraccion = new Extraccion(); extraccion.setCodigoCuentaCliente(cccOrigen); extraccion.setCodigoEntidadBancaria(codigoEntidadBancaria); extraccion.setConcepto(concepto); extraccion.setImporte(importe); extraccion.setPin(credencialesBancarias.getPin()); HttpPost httpPost = new HttpPost(credencialesBancarias.getUrl() + "/retirar"); StringEntity stringEntity = new StringEntity(jsonTransformer.toJson(extraccion)); httpPost.setEntity(stringEntity); httpPost.setHeader("Content-type", "application/json"); httpClient.execute(httpPost); } catch (IOException ex) { Logger.getLogger(BancoCentralServiceImpl.class.getName()).log(Level.SEVERE, null, ex); throw new BusinessException("Error por cuestiones ajenas", "BancoCentral"); } finally { try { httpClient.close(); } catch (IOException ex) { Logger.getLogger(BancoCentralServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:net.troja.eve.producersaid.utils.EveCentral.java
private String getData(final String url) throws IOException { String result = null;/*from w ww.j a v a2 s.c o m*/ if (fileName == null) { final CloseableHttpClient httpclient = HttpClients.createDefault(); final HttpGet request = new HttpGet(url); try { request.setHeader("User-Agent", USER_AGENT); final HttpResponse response = httpclient.execute(request); final int status = response.getStatusLine().getStatusCode(); if ((status >= HttpStatus.SC_OK) && (status < HttpStatus.SC_MULTIPLE_CHOICES)) { final HttpEntity entity = response.getEntity(); if (entity != null) { result = EntityUtils.toString(entity); } } else { throw new IOException( "Download error: " + status + " " + response.getStatusLine().getReasonPhrase()); } } finally { request.reset(); httpclient.close(); } } else { result = new String(Files.readAllBytes(Paths.get(fileName)), "UTF-8"); } return result; }
From source file:org.wso2.mdm.qsg.utils.HTTPInvoker.java
public static HTTPResponse sendHTTPPutWithOAuthSecurity(String url, String payload, HashMap<String, String> headers) { HttpPut put = null;/*from w ww. j a v a 2 s . c om*/ HttpResponse response = null; HTTPResponse httpResponse = new HTTPResponse(); CloseableHttpClient httpclient = null; try { httpclient = (CloseableHttpClient) createHttpClient(); StringEntity requestEntity = new StringEntity(payload, Constants.UTF_8); put = new HttpPut(url); put.setEntity(requestEntity); for (String key : headers.keySet()) { put.setHeader(key, headers.get(key)); } put.setHeader(Constants.Header.AUTH, OAUTH_BEARER + oAuthToken); response = httpclient.execute(put); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); } catch (IOException e) { e.printStackTrace(); } StringBuffer result = new StringBuffer(); String line = ""; try { while ((line = rd.readLine()) != null) { result.append(line); } } catch (IOException e) { e.printStackTrace(); } httpResponse.setResponseCode(response.getStatusLine().getStatusCode()); httpResponse.setResponse(result.toString()); try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } return httpResponse; }
From source file:com.srotya.sidewinder.cluster.storage.ClusteredMemStorageEngine.java
@Override public boolean checkIfExists(String dbName, String measurement) throws Exception { List<String> proxies = new ArrayList<>(); dbName = decodeDbAndProxyNames(proxies, dbName); if (proxies.size() > 0) { return local.checkIfExists(dbName); } else {//from w w w . ja v a2 s. co m boolean localResult = local.checkIfExists(dbName); for (Entry<Integer, WorkerEntry> entry : columbus.getWorkerMap().entrySet()) { if (entry.getKey() != columbus.getSelfWorkerId()) { String newDbName = encodeDbAndProxyName(dbName, String.valueOf(columbus.getSelfWorkerId())); // http call CloseableHttpClient client = Utils.getClient( "http://" + entry.getValue().getWorkerAddress().getHostAddress() + ":8080/", 5000, 5000); // MeasurementOpsApi HttpGet post = new HttpGet("http://" + entry.getValue().getWorkerAddress().getHostAddress() + ":8080/database/" + newDbName + "/" + measurement + "/check"); CloseableHttpResponse result = client.execute(post); if (result.getStatusLine().getStatusCode() == 200) { localResult = true; result.close(); client.close(); break; } } } return localResult; } }