List of usage examples for org.apache.http.impl.client CloseableHttpClient 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);/*w w w. j a va 2s . c om*/ 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:org.thoughtcrime.securesms.mms.MmsConnection.java
protected byte[] makeRequest(boolean useProxy) throws IOException { Log.w(TAG, "connecting to " + apn.getMmsc() + (useProxy ? " using proxy" : "")); HttpUriRequest request;// w ww . j ava2 s . c om CloseableHttpClient client = null; CloseableHttpResponse response = null; try { request = constructRequest(useProxy); client = constructHttpClient(); response = client.execute(request); Log.w(TAG, "* response code: " + response.getStatusLine()); if (response.getStatusLine().getStatusCode() == 200) { return parseResponse(response.getEntity().getContent()); } } finally { if (response != null) response.close(); if (client != null) client.close(); } throw new IOException("unhandled response code"); }
From source file:com.floragunn.searchguard.test.helper.rest.RestHelper.java
protected HttpResponse executeRequest(HttpUriRequest uriRequest, Header... header) throws Exception { CloseableHttpClient httpClient = null; try {/* w ww . j av a 2 s .c o m*/ httpClient = getHTTPClient(); if (header != null && header.length > 0) { for (int i = 0; i < header.length; i++) { Header h = header[i]; uriRequest.addHeader(h); } } HttpResponse res = new HttpResponse(httpClient.execute(uriRequest)); log.trace(res.getBody()); return res; } finally { if (httpClient != null) { httpClient.close(); } } }
From source file:com.worldsmostinterestinginfographic.util.OAuth2Utils.java
/** * Make a protected resource request at the given endpoint with the given access token. * * This method will attempt to access the protected resource with the given access token using the authorization * request header field method. If successful, the full response string will be returned. * * @param resourceEndpoint The endpoint of the protected resource to access * @param accessToken A valid access token with the necessary scopes required to access the protected resource * @return The result string returned in response to the request to access the protected resource with the given token *//* w w w .j ava 2 s . c o m*/ public static String makeProtectedResourceRequest(String resourceEndpoint, String accessToken) { CloseableHttpClient httpClient = HttpClients.createDefault(); try { httpClient = HttpClients.createDefault(); // Add authorization header to POST request HttpPost httpPost = new HttpPost(resourceEndpoint); httpPost.addHeader("Authorization", "Bearer " + accessToken); /* * Note: The addition of the "method=get" URL-encoded form parameter is necessary for the Facebook Graph APIs. * Other OAuth 2 providers may not require this, and some may even reject it. */ List<NameValuePair> urlParameters = new ArrayList<>(); urlParameters.add(new BasicNameValuePair("method", "get")); httpPost.setEntity(new UrlEncodedFormEntity(urlParameters)); // Make the call HttpResponse httpResponse = httpClient.execute(httpPost); // Process the response String response = ""; String currentLine; BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(httpResponse.getEntity().getContent())); while ((currentLine = bufferedReader.readLine()) != null) { response += currentLine; } return response; } catch (IOException e) { log.severe("Fatal exception occurred while making the protected resource request (access token " + LoggingUtils.anonymize(accessToken) + "): " + e.getMessage()); e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { log.severe("Fatal exception occurred while closing HTTP client connection (access token=" + LoggingUtils.anonymize(accessToken) + "): " + e.getMessage()); e.printStackTrace(); } } return null; }
From source file:Remote.java
public String sendCommandRaw(String request) { InputStream response = null;//from w w w. ja v a 2 s . c o m CloseableHttpClient httpClient = HttpClientBuilder.create().build(); String data = "ERROR"; try { try { HttpPost httpRequest = new HttpPost(path); StringEntity httpParams = new StringEntity(request); httpParams.setContentType("application/json"); httpRequest.setEntity(httpParams); response = httpClient.execute(httpRequest).getEntity().getContent(); data = IOUtils.toString(response); } catch (Exception ex) { System.out.println(ex); } finally { httpClient.close(); } } catch (IOException ex) { Logger.getLogger(Remote.class.getName()).log(Level.SEVERE, null, ex); } return data; }
From source file:de.dfki.resc28.serendipity.client.RepresentationEnricher.java
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { OutputStream originalStream = context.getOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); context.setOutputStream(baos);/*from w w w . ja v a 2 s . c o m*/ try { context.proceed(); } finally { // get the original responseModel final Model responseModel = ModelFactory.createDefaultModel(); final String contentType = context.getMediaType().toString(); RDFDataMgr.read(responseModel, new StringReader(baos.toString()), "", RDFLanguages.contentTypeToLang(contentType)); baos.close(); // ask serendipity for affordances to add Model affordances = ModelFactory.createDefaultModel(); StringWriter writer = new StringWriter(); responseModel.write(writer, contentType); StringEntity entity = new StringEntity(writer.toString(), ContentType.create(contentType)); CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(this.serendipityURI); httpPost.setHeader("Accept", contentType); httpPost.setHeader("Content-type", contentType); httpPost.setEntity(entity); CloseableHttpResponse response = client.execute(httpPost); // RDFDataMgr.read(affordances, response.getEntity().getContent(), "", RDFLanguages.contentTypeToLang(response.getEntity().getContentType().getValue())); RDFDataMgr.read(affordances, response.getEntity().getContent(), "", RDFLanguages.contentTypeToLang(contentType)); client.close(); // add the instantiated action to the responseModel responseModel.add(affordances); // overwrite the response ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); RDFDataMgr.write(baos2, responseModel, RDFLanguages.contentTypeToLang(contentType)); baos2.writeTo(originalStream); baos2.close(); context.setOutputStream(originalStream); } }
From source file:org.fedoraproject.jenkins.plugins.copr.CoprClient.java
String doGet(String username, String url) throws CoprException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet(this.apiurl + url); try {/* www .ja v a 2s . com*/ httpget.setHeader("Authorization", "Basic " + Base64.encodeBase64String(String.format("%s:%s", apilogin, apitoken).getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { // here goes trouble throw new AssertionError(e); } String result; try { CloseableHttpResponse response = httpclient.execute(httpget); result = EntityUtils.toString(response.getEntity()); response.close(); httpclient.close(); } catch (IOException e) { throw new CoprException("Error while processing HTTP request", e); } return result; }
From source file:org.opennms.minion.core.impl.ScvEnabledRestClientImpl.java
@Override public void ping() throws Exception { // Setup a client with pre-emptive authentication HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(username, password)); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); try {/* w ww . ja v a 2s. c o m*/ AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(target, basicAuth); HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); // Issue a simple GET against the Info endpoint HttpGet httpget = new HttpGet(url.toExternalForm() + "/rest/info"); CloseableHttpResponse response = httpclient.execute(target, httpget, localContext); response.close(); } finally { httpclient.close(); } }
From source file:Remote.java
public String sendCommand(JSONObject jsonBody) { InputStream response = null;//from w w w. j a va2s.c o m CloseableHttpClient httpClient = HttpClientBuilder.create().build(); String data = "ERROR"; try { try { HttpPost httpRequest = new HttpPost(path); StringEntity httpParams = new StringEntity(jsonBody.toString()); httpParams.setContentType("application/json"); httpRequest.setEntity(httpParams); response = httpClient.execute(httpRequest).getEntity().getContent(); data = IOUtils.toString(response); } catch (Exception ex) { System.out.println(ex); } finally { httpClient.close(); } } catch (IOException ex) { Logger.getLogger(Remote.class.getName()).log(Level.SEVERE, null, ex); } return data; }
From source file:com.github.maoo.indexer.client.WebScriptsAlfrescoClient.java
private String fetchMetadataJson(String nodeUuid) { String fullUrl = String.format("%s/%s", metadataUrl, nodeUuid); logger.debug("url: {}", fullUrl); try {/*from ww w . ja v a 2 s .c o m*/ CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = createGetRequest(fullUrl); CloseableHttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); String result = CharStreams.toString(new InputStreamReader(entity.getContent(), "UTF-8")); response.close(); httpClient.close(); return result; } catch (IOException e) { throw new AlfrescoDownException(e); } }