List of usage examples for org.apache.http.impl.client CloseableHttpClient close
public void close() throws IOException;
From source file:com.kingja.springmvc.util.HttpRequestUtils.java
public String get(String path) { CloseableHttpClient httpclient = HttpClients.createDefault(); try {//from w w w. j av a 2 s .co m // httpget. HttpGet httpget = new HttpGet(path); // get. CloseableHttpResponse response = httpclient.execute(httpget); try { // ?? HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity); } } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // ,? try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return ""; }
From source file:org.apache.hadoop.gateway.GatewaySslFuncTest.java
@Test(timeout = TestUtils.MEDIUM_TIMEOUT) public void testKnox674SslCipherSuiteConfig() throws Exception { LOG_ENTER();//from ww w . jav a 2 s . c o m String topoStr = TestUtils.merge(DAT, "test-admin-topology.xml", params); File topoFile = new File(config.getGatewayTopologyDir(), "test-topology.xml"); FileUtils.writeStringToFile(topoFile, topoStr); topos.reloadTopologies(); String username = "guest"; String password = "guest-password"; String serviceUrl = gatewayUrl + "/test-topology/api/v1/version"; HttpHost targetHost = new HttpHost("localhost", gatewayPort, gatewayScheme); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); CloseableHttpClient client = HttpClients.custom() .setSSLSocketFactory( new SSLConnectionSocketFactory(createInsecureSslContext(), new String[] { "TLSv1.2" }, new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }, new TrustAllHosts())) .build(); HttpGet request = new HttpGet(serviceUrl); CloseableHttpResponse response = client.execute(request, context); assertThat(the(new StreamSource(response.getEntity().getContent())), hasXPath("/ServerVersion/version")); response.close(); client.close(); gateway.stop(); config.setExcludedSSLCiphers(Arrays.asList(new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" })); config.setIncludedSSLCiphers(Arrays.asList(new String[] { "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" })); startGatewayServer(); serviceUrl = gatewayUrl + "/test-topology/api/v1/version"; try { client = HttpClients.custom() .setSSLSocketFactory( new SSLConnectionSocketFactory(createInsecureSslContext(), new String[] { "TLSv1.2" }, new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" }, new TrustAllHosts())) .build(); request = new HttpGet(serviceUrl); client.execute(request, context); fail("Expected SSLHandshakeException"); } catch (SSLHandshakeException e) { // Expected. client.close(); } client = HttpClients.custom() .setSSLSocketFactory( new SSLConnectionSocketFactory(createInsecureSslContext(), new String[] { "TLSv1.2" }, new String[] { "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" }, new TrustAllHosts())) .build(); request = new HttpGet(serviceUrl); response = client.execute(request, context); assertThat(the(new StreamSource(response.getEntity().getContent())), hasXPath("/ServerVersion/version")); response.close(); client.close(); LOG_EXIT(); }
From source file:org.fedoraproject.jenkins.plugins.copr.CoprClient.java
private String doPost(String username, String coprname, List<NameValuePair> params, String url) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(new URL(apiurl, url).toString()); try {/*from ww w .j a va 2 s . c o m*/ httppost.setHeader("Authorization", "Basic " + Base64 .encodeBase64String(String.format("%s:%s", this.apilogin, this.apitoken).getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { // here goes trouble throw new AssertionError(e); } if (params != null) { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, Consts.UTF_8); httppost.setEntity(entity); } String result; CloseableHttpResponse response = httpclient.execute(httppost); result = EntityUtils.toString(response.getEntity()); response.close(); httpclient.close(); return result; }
From source file:com.kingmed.dp.ndp.NDPConnectionManager.java
@Override public void connect() throws Exception { String signinUrl = ndpServe.getUrlSignin(); CloseableHttpClient httpclient = HttpClients.createDefault(); try {/* w ww. j a v a 2 s .c o m*/ HttpGet httpget = new HttpGet(signinUrl); String responseBody = httpclient.execute(httpget, new ResponseHandler<String>() { @Override public String handleResponse(HttpResponse hr) throws ClientProtocolException, IOException { int status = hr.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = hr.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }); } catch (Exception e) { e.printStackTrace(); } finally { httpclient.close(); } }
From source file:org.gradle.cache.tasks.http.HttpTaskOutputCache.java
@Override public boolean load(TaskCacheKey key, TaskOutputReader reader) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); try {/*from w w w. ja v a2 s . c o m*/ final URI uri = root.resolve("./" + key.getHashCode()); HttpGet httpGet = new HttpGet(uri); final CloseableHttpResponse response = httpClient.execute(httpGet); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Response for GET {}: {}", uri, response.getStatusLine()); } try { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { reader.readFrom(response.getEntity().getContent()); return true; } else { return false; } } finally { response.close(); } } finally { httpClient.close(); } }
From source file:Vdisk.java
public void download_file(String filepath, String local_filepath) throws URISyntaxException, IOException { URI uri = new URIBuilder().setScheme("https").setHost("api.weipan.cn/2/files/sandbox/").setPath(filepath) .setParameter("access_token", this.access_token).build(); CloseableHttpClient getClient = HttpClients.createDefault(); if (access_token == null) this.get_access_token(); HttpGet httpGet = new HttpGet(uri); try (CloseableHttpResponse response = getClient.execute(httpGet)) { StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == 200) { File file = new File(local_filepath); try (FileOutputStream fout = new FileOutputStream(file)) { String content = EntityUtils.toString(response.getEntity()); System.out.println(content.length()); byte contents[] = content.getBytes(Charset.forName("ISO-8859-1")); fout.write(contents);/*from w w w. j a va 2s.co m*/ } } } finally { getClient.close(); } }
From source file:org.ops4j.pax.web.itest.base.HttpTestClient.java
public boolean checkServer(String path) throws Exception { LOG.info("checking server path {}", path); HttpGet httpget = null;//from www.j a va2 s . c o m CloseableHttpClient myHttpClient = createHttpClient(); HttpHost targetHost = getHttpHost(path); httpget = new HttpGet("/"); httpget.addHeader("Accept-Language", "en-us;q=0.8,en;q=0.5"); LOG.info("calling remote {}://{}:{}/ ...", new Object[] { targetHost.getSchemeName(), targetHost.getHostName(), targetHost.getPort() }); HttpResponse response = null; try { response = myHttpClient.execute(targetHost, httpget); } catch (IOException ioe) { LOG.info("... caught IOException"); return false; } finally { myHttpClient.close(); } int statusCode = response.getStatusLine().getStatusCode(); LOG.info("... responded with: {}", statusCode); return statusCode == 404 || statusCode == 200; }
From source file:org.nuxeo.connect.connector.http.ConnectHttpConnector.java
@Override protected ConnectServerResponse execServerCall(String url, Map<String, String> headers) throws ConnectServerError { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); ProxyHelper.configureProxyIfNeeded(httpClientBuilder, url); httpClientBuilder.setConnectionTimeToLive(connectHttpTimeout, TimeUnit.MILLISECONDS); HttpGet method = new HttpGet(url); for (String name : headers.keySet()) { method.addHeader(name, headers.get(name)); }/* www . j av a2 s. com*/ CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; try { // We do not use autoclose on the httpClient nor on the httpResponse since we may return them yet // not consumed in the ConnectHttpResponse httpClient = httpClientBuilder.build(); httpResponse = httpClient.execute(method); int rc = httpResponse.getStatusLine().getStatusCode(); switch (rc) { case HttpStatus.SC_OK: case HttpStatus.SC_NO_CONTENT: case HttpStatus.SC_NOT_FOUND: return new ConnectHttpResponse(httpClient, httpResponse); case HttpStatus.SC_UNAUTHORIZED: httpResponse.close(); httpClient.close(); throw new ConnectSecurityError("Connect server refused authentication (returned 401)"); case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED: httpResponse.close(); httpClient.close(); throw new ConnectSecurityError("Proxy server require authentication (returned 407)"); case HttpStatus.SC_GATEWAY_TIMEOUT: case HttpStatus.SC_REQUEST_TIMEOUT: httpResponse.close(); httpClient.close(); throw new ConnectServerError("Timeout " + rc); default: try { String body = EntityUtils.toString(httpResponse.getEntity()); JSONObject obj = new JSONObject(body); String message = obj.getString("message"); String errorClass = obj.getString("errorClass"); ConnectServerError error; if (ConnectSecurityError.class.getSimpleName().equals(errorClass)) { error = new ConnectSecurityError(message); } else if (ConnectClientVersionMismatchError.class.getSimpleName().equals(errorClass)) { error = new ConnectClientVersionMismatchError(message); } else { error = new ConnectServerError(message); } throw error; } catch (JSONException e) { log.debug("Can't parse server error " + rc, e); throw new ConnectServerError("Server returned a code " + rc); } finally { httpResponse.close(); httpClient.close(); } } } catch (ConnectServerError cse) { throw cse; } catch (IOException e) { IOUtils.closeQuietly(httpResponse); IOUtils.closeQuietly(httpClient); throw new ConnectServerError("Error during communication with the Nuxeo Connect Server", e); } }
From source file:Onlinedata.MainSendRequest.java
public void downloadData(String filename) { downloadurl = baseurl + filename;/* w w w. j a va 2s .co m*/ try { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet(downloadurl); CloseableHttpResponse response = httpclient.execute(httpget); try { response = httpclient.execute(httpget); HttpEntity serverEntity = response.getEntity(); if (serverEntity != null) { System.out.println("Found file at adress: " + downloadurl); long len = serverEntity.getContentLength(); System.out.println("Length is " + len); download = EntityUtils.toString(serverEntity); System.out.println(download); } } 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.sasabus.export2Freegis.network.SubscriptionManager.java
public void unsubscribe() throws IOException { Scanner sc = new Scanner(new File(UNSUBSCRIPTIONFILE)); String subscriptionstring = ""; while (sc.hasNextLine()) { subscriptionstring += sc.nextLine(); }/*from ww w .j av a2 s .c om*/ sc.close(); SimpleDateFormat date_date = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat date_time = new SimpleDateFormat("HH:mm:ssZ"); Date d = new Date(); String timestamp = date_date.format(d) + "T" + date_time.format(d); timestamp = timestamp.substring(0, timestamp.length() - 2) + ":" + timestamp.substring(timestamp.length() - 2); subscriptionstring = subscriptionstring.replaceAll(":timestamp", timestamp); String requestString = "http://" + this.address + ":" + this.portnumber_sender + "/TmEvNotificationService/gms/subscription.xml"; HttpPost subrequest = new HttpPost(requestString); StringEntity requestEntity = new StringEntity(subscriptionstring, ContentType.create("text/xml", "ISO-8859-1")); CloseableHttpClient httpClient = HttpClients.createDefault(); subrequest.setEntity(requestEntity); CloseableHttpResponse response = httpClient.execute(subrequest); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { try { System.out.println("Stauts Response: " + response.getStatusLine().getStatusCode()); System.out.println("Status Phrase: " + response.getStatusLine().getReasonPhrase()); HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { String responsebody = EntityUtils.toString(responseEntity); System.out.println(responsebody); } } finally { response.close(); httpClient.close(); } } }