Example usage for org.apache.http.impl.client CloseableHttpClient close

List of usage examples for org.apache.http.impl.client CloseableHttpClient close

Introduction

In this page you can find the example usage for org.apache.http.impl.client CloseableHttpClient close.

Prototype

public void close() throws IOException;

Source Link

Document

Closes this stream and releases any system resources associated with it.

Usage

From source file:org.apache.synapse.samples.framework.clients.BasicHttpClient.java

/**
 * Make a HTTP OPTIONS request on the specified URL.
 *
 * @param url A valid HTTP URL//from   w w  w .  ja  va 2 s .c  o  m
 * @return A HttpResponse object
 * @throws Exception If an error occurs while making the HTTP call
 */
public HttpResponse doOptions(String url) throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    try {
        HttpOptions options = new HttpOptions(url);
        return new HttpResponse(client.execute(options));
    } finally {
        client.close();
    }
}

From source file:ar.com.colo.rest.test.RestletTestSupport.java

public HttpResponse doExecute(HttpUriRequest method) throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    try {/* ww  w.  jav  a  2 s  . c o m*/
        HttpResponse response = client.execute(method);
        response.setEntity(new BufferedHttpEntity(response.getEntity()));
        return response;
    } finally {
        client.close();
    }
}

From source file:net.ychron.unirestinst.http.UnirestInst.java

/**
 * Close the asynchronous client and its event loop. Use this method to close all the threads and allow an application to exit.
 *///from www . ja  v  a  2 s  .  c  o  m
public void shutdown() throws IOException {
    // Closing the Sync HTTP client
    CloseableHttpClient syncClient = (CloseableHttpClient) options.getOption(Option.HTTPCLIENT);
    if (syncClient != null) {
        syncClient.close();
    }

    SyncIdleConnectionMonitorThread syncIdleConnectionMonitorThread = (SyncIdleConnectionMonitorThread) options
            .getOption(Option.SYNC_MONITOR);
    if (syncIdleConnectionMonitorThread != null) {
        syncIdleConnectionMonitorThread.interrupt();
    }

    // Closing the Async HTTP client (if running)
    CloseableHttpAsyncClient asyncClient = (CloseableHttpAsyncClient) options.getOption(Option.ASYNCHTTPCLIENT);
    if (asyncClient != null && asyncClient.isRunning()) {
        asyncClient.close();
    }

    AsyncIdleConnectionMonitorThread asyncMonitorThread = (AsyncIdleConnectionMonitorThread) options
            .getOption(Option.ASYNC_MONITOR);
    if (asyncMonitorThread != null) {
        asyncMonitorThread.interrupt();
    }
}

From source file:edu.lternet.pasta.client.PastaClient.java

protected void closeHttpClient(CloseableHttpClient httpClient) {
    try {//from  w  ww . j av a2s.c  o  m
        httpClient.close();
    } catch (IOException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }
}

From source file:org.miloss.fgsms.presentation.StatusHelper.java

/**
 * determines if an fgsms service is currently accessible. not for use
 * with other services.// ww  w  .j  ava 2s . com
 *
 * @param endpoint
 * @return
 */
public String sendGetRequest(String endpoint) {
    //   String result = null;
    if (endpoint.startsWith("http")) {
        // Send a GET request to the servlet
        try {

            URL url = new URL(endpoint);
            int port = url.getPort();
            if (port <= 0) {
                if (endpoint.startsWith("https:")) {
                    port = 443;
                } else {
                    port = 80;
                }
            }

            HttpClientBuilder create = HttpClients.custom();

            if (mode == org.miloss.fgsms.common.Constants.AuthMode.UsernamePassword) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(url.getHost(), port),
                        new UsernamePasswordCredentials(username, Utility.DE(password)));
                create.setDefaultCredentialsProvider(credsProvider);
                ;

            }
            CloseableHttpClient c = create.build();

            CloseableHttpResponse response = c.execute(new HttpHost(url.getHost(), port),
                    new HttpGet(endpoint));

            c.close();
            int status = response.getStatusLine().getStatusCode();
            if (status == 200) {
                return "OK";
            }
            return String.valueOf(status);

        } catch (Exception ex) {
            Logger.getLogger(Helper.class).log(Level.WARN,
                    "error fetching http doc from " + endpoint + ex.getLocalizedMessage());
            return "offline";
        }
    } else {
        return "undeterminable";
    }
}

From source file:com.restfiddle.handler.http.DeleteHandler.java

public RfResponseDTO process(RfRequestDTO rfRequestDTO) throws IOException {
    RfResponseDTO response = null;//from w ww.ja v  a 2s  .  c om
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpDelete httpDelete = new HttpDelete(rfRequestDTO.getApiUrl());
    httpDelete.addHeader("Content-Type", "application/json");
    try {
        response = processHttpRequest(httpDelete, httpclient);
    } finally {
        httpclient.close();
    }
    return response;
}

From source file:com.safestream.sdk.http.SafeStreamHttpClient.java

private void tryCloseHttpClient(CloseableHttpClient httpClient) throws SafeStreamHttpClientException {
    try {/*  w ww .  j av a  2  s .  c  o  m*/
        httpClient.close();
    } catch (IOException e) {
        throw new SafeStreamHttpClientException(e);
    }
}

From source file:gda.util.ElogEntry.java

/**
 * Creates an ELog entry. Default ELog server is "http://rdb.pri.diamond.ac.uk/devl/php/elog/cs_logentryext_bl.php"
 * which is the development database. "http://rdb.pri.diamond.ac.uk/php/elog/cs_logentryext_bl.php" is the
 * production database. The java.properties file contains the property "gda.elog.targeturl" which can be set to be
 * either the development or production databases.
 * /*from w w w.j  a v  a 2 s.c  o  m*/
 * @param title
 *            The ELog title
 * @param content
 *            The ELog content
 * @param userID
 *            The user ID e.g. epics or gda or abc12345
 * @param visit
 *            The visit number
 * @param logID
 *            The type of log book, The log book ID: Beam Lines: - BLB16, BLB23, BLI02, BLI03, BLI04, BLI06, BLI11,
 *            BLI16, BLI18, BLI19, BLI22, BLI24, BLI15, DAG = Data Acquisition, EHC = Experimental Hall
 *            Coordinators, OM = Optics and Meteorology, OPR = Operations, E
 * @param groupID
 *            The group sending the ELog, DA = Data Acquisition, EHC = Experimental Hall Coordinators, OM = Optics
 *            and Meteorology, OPR = Operations CS = Control Systems, GroupID Can also be a beam line,
 * @param fileLocations
 *            The image file names with path to upload
 * @throws ELogEntryException
 */
public static void post(String title, String content, String userID, String visit, String logID, String groupID,
        String[] fileLocations) throws ELogEntryException {
    String targetURL = POST_UPLOAD_URL;
    try {
        String entryType = "41";// entry type is always a log (41)
        String titleForPost = visit == null ? title : "Visit: " + visit + " - " + title;

        MultipartEntityBuilder request = MultipartEntityBuilder.create().addTextBody("txtTITLE", titleForPost)
                .addTextBody("txtCONTENT", content).addTextBody("txtLOGBOOKID", logID)
                .addTextBody("txtGROUPID", groupID).addTextBody("txtENTRYTYPEID", entryType)
                .addTextBody("txtUSERID", userID);

        if (fileLocations != null) {
            for (int i = 1; i < fileLocations.length + 1; i++) {
                File targetFile = new File(fileLocations[i - 1]);
                request = request.addBinaryBody("userfile" + i, targetFile, ContentType.create("image/png"),
                        targetFile.getName());
            }
        }

        HttpEntity entity = request.build();
        targetURL = LocalProperties.get("gda.elog.targeturl", POST_UPLOAD_URL);
        HttpPost httpPost = new HttpPost(targetURL);
        httpPost.setEntity(entity);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(httpPost);

        try {
            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 = " + targetURL + " titleForPost = "
                        + titleForPost + " logID = " + logID + " groupID = " + groupID + " entryType = "
                        + entryType + " userID = " + userID);
            }
        } finally {
            response.close();
            httpClient.close();
        }
    } catch (ELogEntryException e) {
        throw e;
    } catch (Exception e) {
        throw new ELogEntryException("Error in ELogger.  Database:" + targetURL, e);
    }
}

From source file:Vdisk.java

public void upload_file(String local_filepath, String filepath)
        throws URISyntaxException, FileNotFoundException, IOException {
    File file = new File(local_filepath);
    URI uri = new URIBuilder().setScheme("http").setHost("upload-vdisk.sina.com.cn/2/files/sandbox/")
            .setPath(filepath).setParameter("access_token", this.access_token).build();
    HttpPost httpPost = new HttpPost(uri);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, local_filepath);
    HttpEntity entity = builder.build();
    httpPost.setEntity(entity);//  ww w .  java 2s .  c om
    CloseableHttpClient postClient = HttpClients.createDefault();
    try (CloseableHttpResponse response = postClient.execute(httpPost)) {
        System.out.println(response);//check result
    } finally {
        postClient.close();
    }
}

From source file:org.talend.dataprofiler.help.RegexExpeHelpUrlTest.java

private StatusLine execute(String helpUrl) throws ClientProtocolException, IOException {
    StatusLine statusLine = null;//from   w w w. j  av  a 2s.  c  om
    CloseableHttpClient httpclient = HttpClients.createMinimal();
    try {
        HttpGet httpget = new HttpGet(helpUrl);
        CloseableHttpResponse execute = httpclient.execute(httpget);
        statusLine = execute.getStatusLine();

    } finally {
        httpclient.close();
    }
    return statusLine;
}