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 doPost(String url, String content) throws Exception { CloseableHttpClient _httpClient = __doBuildHttpClient(); try {//from ww w .j a va2 s.c o m _LOG.debug("Request URL [" + url + "] PostBody [" + content + "]"); String _result = _httpClient.execute( RequestBuilder.post().setUri(url) .setEntity(EntityBuilder.create().setContentEncoding(DEFAULT_CHARSET) .setContentType(ContentType.create("application/x-www-form-urlencoded", DEFAULT_CHARSET)) .setText(content).build()) .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:org.pepstock.jem.commands.util.HttpUtil.java
/** * Calls a http node of JEM to get all members of group, necessary to client * to connect to JEM./*w w w . ja va 2 s . co m*/ * * @param url http URL to call * @return Arrays with all members of Hazelcast cluster * @throws SubmitException if errors occur */ public static String[] getMembers(String url) throws SubmitException { // creates a HTTP client CloseableHttpClient httpclient = null; try { httpclient = createHttpClient(url); // concats URL with query string String completeUrl = url + HttpUtil.MEMBERS_QUERY_STRING; // prepares GET request and basic response handler HttpGet httpget = new HttpGet(completeUrl); CloseableHttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { long len = entity.getContentLength(); if (len != -1 && len < 2048) { // executes and parse the results // result must be // [ipaddress:port],[ipaddress:port],[ipaddress:port],....[ipaddress:port] return EntityUtils.toString(entity).trim().split(","); } else { throw new IOException("HTTP Entity content length wrong: " + len); } } throw new IOException("HTTP Entity is null"); } catch (KeyManagementException e) { throw new SubmitException(SubmitMessage.JEMW001E, e); } catch (UnrecoverableKeyException e) { throw new SubmitException(SubmitMessage.JEMW001E, e); } catch (NoSuchAlgorithmException e) { throw new SubmitException(SubmitMessage.JEMW001E, e); } catch (KeyStoreException e) { throw new SubmitException(SubmitMessage.JEMW001E, e); } catch (URISyntaxException e) { throw new SubmitException(SubmitMessage.JEMW001E, e); } catch (ClientProtocolException e) { throw new SubmitException(SubmitMessage.JEMW001E, e); } catch (IOException e) { throw new SubmitException(SubmitMessage.JEMW001E, e); } finally { // close http client if (httpclient != null) { try { httpclient.close(); } catch (IOException e) { LogAppl.getInstance().ignore(e.getMessage(), e); } } } }
From source file:net.ymate.platform.module.wechat.support.HttpClientHelper.java
public String doPost(String url, byte[] content) throws Exception { CloseableHttpClient _httpClient = __doBuildHttpClient(); try {/*from w w w .j a v a 2s . c o m*/ _LOG.debug("Request URL [" + url + "] PostBody [" + content + "]"); String _result = _httpClient.execute( RequestBuilder.post().setUri(url) .setEntity(EntityBuilder.create().setContentEncoding(DEFAULT_CHARSET) .setContentType(ContentType.create("application/x-www-form-urlencoded", DEFAULT_CHARSET)) .setBinary(content).build()) .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:ru.neverdark.yotta.parser.YottaParser.java
private void parse(Array array) { final String URL = String.format("http://%s/hierarch.htm", array.getIp()); final StringBuffer result = new StringBuffer(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(array.getIp(), 80), new UsernamePasswordCredentials(array.getUser(), array.getPassword())); CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); try {//ww w . j a va2s . c om HttpGet httpget = new HttpGet(URL); CloseableHttpResponse response = httpClient.execute(httpget); System.err.printf("%s\t%s\n", array.getIp(), response.getStatusLine()); try { BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } Document doc = Jsoup.parse(result.toString()); Elements tables = doc.getElementsByAttribute("vspace"); // skip first for (int i = 1; i < tables.size(); i++) { parseTable(tables.get(i), array.getType()); } } finally { response.close(); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:com.dawg6.d3api.server.D3IO.java
public Account getAccount(Token token) throws Exception { CloseableHttpClient client = HttpClientBuilder.create().build(); URIBuilder builder = new URIBuilder(ACCOUNT_API_URL); builder.addParameter("access_token", token.access_token); // log.info("Request = " + builder.toString()); HttpGet request = new HttpGet(builder.toString()); 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 ww . j a v a 2s . c o 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); Account account = mapper.readValue(result.toString(), Account.class); if ((account != null) && (account.error != null)) throw new RuntimeException(token.error_description); return account; }
From source file:org.asqatasun.util.http.HttpRequestHandler.java
public String getHttpContent(String url) throws URISyntaxException, UnknownHostException, IOException, IllegalCharsetNameException { if (StringUtils.isEmpty(url)) { return ""; }//from w ww .j a va 2 s .c o m String encodedUrl = getEncodedUrl(url); CloseableHttpClient httpClient = getHttpClient(encodedUrl); HttpGet get = new HttpGet(encodedUrl); try { LOGGER.debug("executing request to retrieve content on " + get.getURI()); HttpResponse response = httpClient.execute(get); LOGGER.debug("received " + response.getStatusLine().getStatusCode() + " from get request"); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { LOGGER.debug("status == HttpStatus.SC_OK "); return EntityUtils.toString(response.getEntity(), Charset.defaultCharset()); } else { LOGGER.debug("status != HttpStatus.SC_OK "); return ""; } } catch (NullPointerException ioe) { LOGGER.debug("NullPointerException"); return ""; } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources get.releaseConnection(); LOGGER.debug("finally"); httpClient.close(); } }
From source file:org.asqatasun.util.http.HttpRequestHandler.java
public int getHttpStatusFromGet(String url) throws IOException { String encodedUrl = getEncodedUrl(url); CloseableHttpClient httpClient = getHttpClient(encodedUrl); HttpGet get = new HttpGet(encodedUrl); try {//from w w w . jav a2 s . com LOGGER.debug("executing get request to retrieve status on " + get.getURI()); HttpResponse status = httpClient.execute(get); if (LOGGER.isDebugEnabled()) { LOGGER.debug("received " + status + " from get request"); for (Header h : get.getAllHeaders()) { LOGGER.debug("header : " + h.getName() + " " + h.getValue()); } } return status.getStatusLine().getStatusCode(); } catch (UnknownHostException uhe) { LOGGER.warn("UnknownHostException on " + encodedUrl); return HttpStatus.SC_NOT_FOUND; } catch (IOException ioe) { LOGGER.warn("IOException on " + encodedUrl); return HttpStatus.SC_NOT_FOUND; } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources get.releaseConnection(); httpClient.close(); } }
From source file:net.maritimecloud.identityregistry.utils.KeycloakServiceAccountUtil.java
/** * Fetches and returns data on an IDP/*from w w w.j a va 2s . c o m*/ * * @param name name of the IDP * @return */ public IdentityProviderRepresentation getIDP(String name) { CloseableHttpClient client = HttpClientBuilder.create().build(); try { HttpGet get = new HttpGet(baseUrl + "/admin/realms/" + realm + "/identity-provider/instances/" + name); get.addHeader("Authorization", "Bearer " + token); try { HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() != 200) { System.out.println(response.getStatusLine().getStatusCode()); return null; } HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); try { return JsonSerialization.readValue(is, IdentityProviderRepresentation.class); } finally { is.close(); } } catch (IOException e) { throw new RuntimeException(e); } } finally { try { client.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:de.adesso.referencer.search.helper.MyHelpMethods.java
public static String sendHttpRequest2(String url, String requestBody, String requestType) throws IOException { String result = null;/*from w w w .jav a2s.c o m*/ CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse httpResponse; try { switch (requestType) { case "Get": httpResponse = httpclient.execute(new HttpGet(url)); break; case "Post": HttpPost httppost = new HttpPost(url); if (requestBody != null) { httppost.setEntity(new StringEntity(requestBody)); } httpResponse = httpclient.execute(httppost); break; case "Put": HttpPut httpPut = new HttpPut(url); httpPut.addHeader("Content-Type", "application/json"); httpPut.addHeader("Accept", "application/json"); if (requestBody != null) { httpPut.setEntity(new StringEntity(requestBody, DEFAULT_CHARSET)); } httpResponse = httpclient.execute(httpPut); break; case "Delete": httpResponse = httpclient.execute(new HttpDelete(url)); break; default: httpResponse = httpclient.execute(new HttpGet(url)); break; } try { HttpEntity entity1 = httpResponse.getEntity(); if (entity1 != null) { long len = entity1.getContentLength(); if (len != -1 && len < MAX_CONTENT_LENGTH) { result = EntityUtils.toString(entity1, DEFAULT_CHARSET); } else { System.out.println("Error!!!! entity length=" + len); } } EntityUtils.consume(entity1); } finally { httpResponse.close(); } } catch (Exception e) { e.printStackTrace(); } finally { httpclient.close(); } return result; }
From source file:com.mollie.api.MollieClient.java
/** * Perform a http call. This method is used by the resource specific classes. * Please use the payments() method to perform operations on payments. * * @param method the http method to use/*from ww w.j a va 2s . c o m*/ * @param apiMethod the api method to call * @param httpBody the contents to send to the server. * @return result of the http call * @throws MollieException when the api key is not set or when there is a * problem communicating with the mollie server. * @see #performHttpCall(String method, String apiMethod) */ public String performHttpCall(String method, String apiMethod, String httpBody) throws MollieException { URI uri = null; String result = null; if (_apiKey == null || _apiKey.trim().equals("")) { throw new MollieException("You have not set an api key. Please use setApiKey() to set the API key."); } try { URIBuilder ub = new URIBuilder(this._apiEndpoint + "/" + API_VERSION + "/" + apiMethod); uri = ub.build(); } catch (URISyntaxException e) { e.printStackTrace(); } if (uri != null) { CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpRequestBase action = null; HttpResponse response = null; if (method.equals(HTTP_POST)) { action = new HttpPost(uri); } else if (method.equals(HTTP_DELETE)) { action = new HttpDelete(uri); } else { action = new HttpGet(uri); } if (httpBody != null && action instanceof HttpPost) { StringEntity entity = new StringEntity(httpBody, ContentType.APPLICATION_JSON); ((HttpPost) action).setEntity(entity); } action.setHeader("Authorization", "Bearer " + this._apiKey); action.setHeader("Accept", ContentType.APPLICATION_JSON.getMimeType()); try { response = httpclient.execute(action); HttpEntity entity = response.getEntity(); StringWriter sw = new StringWriter(); IOUtils.copy(entity.getContent(), sw, "UTF-8"); result = sw.toString(); EntityUtils.consume(entity); } catch (Exception e) { throw new MollieException("Unable to communicate with Mollie"); } try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return result; }