Example usage for org.apache.http.client.methods CloseableHttpResponse close

List of usage examples for org.apache.http.client.methods CloseableHttpResponse close

Introduction

In this page you can find the example usage for org.apache.http.client.methods CloseableHttpResponse 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:com.frochr123.fabqr.FabQRFunctions.java

public static void uploadFabQRProject(String name, String email, String projectName, int licenseIndex,
        String tools, String description, String location, BufferedImage imageReal, BufferedImage imageScheme,
        PlfFile plfFile, String lasercutterName, String lasercutterMaterial) throws Exception {
    // Check for valid situation, otherwise abort
    if (MainView.getInstance() == null || VisicutModel.getInstance() == null
            || VisicutModel.getInstance().getPlfFile() == null || !isFabqrActive()
            || getFabqrPrivateURL() == null || getFabqrPrivateURL().isEmpty()
            || MaterialManager.getInstance() == null || MappingManager.getInstance() == null
            || VisicutModel.getInstance().getSelectedLaserDevice() == null) {
        throw new Exception("FabQR upload exception: Critical error");
    }/*from   w w  w  .j  av a  2s .c  om*/

    // Check valid data
    if (name == null || email == null || projectName == null || projectName.length() < 3 || licenseIndex < 0
            || tools == null || tools.isEmpty() || description == null || description.isEmpty()
            || location == null || location.isEmpty() || imageScheme == null || plfFile == null
            || lasercutterName == null || lasercutterName.isEmpty() || lasercutterMaterial == null
            || lasercutterMaterial.isEmpty()) {
        throw new Exception("FabQR upload exception: Invalid input data");
    }

    // Convert images to byte data for PNG, imageReal is allowed to be empty
    byte[] imageSchemeBytes = null;
    ByteArrayOutputStream imageSchemeOutputStream = new ByteArrayOutputStream();
    PreviewImageExport.writePngToOutputStream(imageSchemeOutputStream, imageScheme);
    imageSchemeBytes = imageSchemeOutputStream.toByteArray();

    if (imageSchemeBytes == null) {
        throw new Exception("FabQR upload exception: Error converting scheme image");
    }

    byte[] imageRealBytes = null;

    if (imageReal != null) {
        // Need to convert image, ImageIO.write messes up the color space of the original input image
        BufferedImage convertedImage = new BufferedImage(imageReal.getWidth(), imageReal.getHeight(),
                BufferedImage.TYPE_3BYTE_BGR);
        ColorConvertOp op = new ColorConvertOp(null);
        op.filter(imageReal, convertedImage);

        ByteArrayOutputStream imageRealOutputStream = new ByteArrayOutputStream();
        ImageIO.write(convertedImage, "jpg", imageRealOutputStream);
        imageRealBytes = imageRealOutputStream.toByteArray();
    }

    // Extract all URLs from used QR codes
    List<String> referencesList = new LinkedList<String>();
    List<PlfPart> plfParts = plfFile.getPartsCopy();

    for (PlfPart plfPart : plfParts) {
        if (plfPart.getQRCodeInfo() != null && plfPart.getQRCodeInfo().getQRCodeSourceURL() != null
                && !plfPart.getQRCodeInfo().getQRCodeSourceURL().trim().isEmpty()) {
            // Process url, if it is URL of a FabQR system, remove download flag and point to project page instead
            // Use regex to check for FabQR system URL structure
            String qrCodeUrl = plfPart.getQRCodeInfo().getQRCodeSourceURL().trim();

            // Check for temporary URL structure of FabQR system
            Pattern fabQRUrlTemporaryPattern = Pattern
                    .compile("^https{0,1}://.*?" + "/" + FABQR_TEMPORARY_MARKER + "/" + "([a-z]|[0-9]){7,7}$");

            // Do not include link if it is just temporary
            if (fabQRUrlTemporaryPattern.matcher(qrCodeUrl).find()) {
                continue;
            }

            // Check for download URL structure of FabQR system
            // Change URL to point to project page instead
            Pattern fabQRUrlDownloadPattern = Pattern
                    .compile("^https{0,1}://.*?" + "/" + FABQR_DOWNLOAD_MARKER + "/" + "([a-z]|[0-9]){7,7}$");

            if (fabQRUrlDownloadPattern.matcher(qrCodeUrl).find()) {
                qrCodeUrl = qrCodeUrl.replace("/" + FABQR_DOWNLOAD_MARKER + "/", "/");
            }

            // Add URL if it is not yet in list
            if (!referencesList.contains(qrCodeUrl)) {
                referencesList.add(qrCodeUrl);
            }
        }
    }

    String references = "";

    for (String ref : referencesList) {
        // Add comma for non first entries
        if (!references.isEmpty()) {
            references = references + ",";
        }

        references = references + ref;
    }

    // Get bytes for PLF file
    byte[] plfFileBytes = null;
    ByteArrayOutputStream plfFileOutputStream = new ByteArrayOutputStream();
    VisicutModel.getInstance().savePlfToStream(MaterialManager.getInstance(), MappingManager.getInstance(),
            plfFileOutputStream);
    plfFileBytes = plfFileOutputStream.toByteArray();

    if (plfFileBytes == null) {
        throw new Exception("FabQR upload exception: Error saving PLF file");
    }

    // Begin uploading data
    String uploadUrl = getFabqrPrivateURL() + FABQR_API_UPLOAD_PROJECT;

    // Create HTTP client and cusomized config for timeouts
    CloseableHttpClient httpClient = HttpClients.createDefault();
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(FABQR_UPLOAD_TIMEOUT)
            .setConnectTimeout(FABQR_UPLOAD_TIMEOUT).setConnectionRequestTimeout(FABQR_UPLOAD_TIMEOUT).build();

    // Create HTTP Post request and entity builder
    HttpPost httpPost = new HttpPost(uploadUrl);
    httpPost.setConfig(requestConfig);
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

    // Insert file uploads
    multipartEntityBuilder.addBinaryBody("imageScheme", imageSchemeBytes, ContentType.APPLICATION_OCTET_STREAM,
            "imageScheme.png");
    multipartEntityBuilder.addBinaryBody("inputFile", plfFileBytes, ContentType.APPLICATION_OCTET_STREAM,
            "inputFile.plf");

    // Image real is allowed to be null, if it is not, send it
    if (imageRealBytes != null) {
        multipartEntityBuilder.addBinaryBody("imageReal", imageRealBytes, ContentType.APPLICATION_OCTET_STREAM,
                "imageReal.png");
    }

    // Prepare content type for text data, especially needed for correct UTF8 encoding
    ContentType contentType = ContentType.create("text/plain", Consts.UTF_8);

    // Insert text data
    multipartEntityBuilder.addTextBody("name", name, contentType);
    multipartEntityBuilder.addTextBody("email", email, contentType);
    multipartEntityBuilder.addTextBody("projectName", projectName, contentType);
    multipartEntityBuilder.addTextBody("licenseIndex", new Integer(licenseIndex).toString(), contentType);
    multipartEntityBuilder.addTextBody("tools", tools, contentType);
    multipartEntityBuilder.addTextBody("description", description, contentType);
    multipartEntityBuilder.addTextBody("location", location, contentType);
    multipartEntityBuilder.addTextBody("lasercutterName", lasercutterName, contentType);
    multipartEntityBuilder.addTextBody("lasercutterMaterial", lasercutterMaterial, contentType);
    multipartEntityBuilder.addTextBody("references", references, contentType);

    // Assign entity to this post request
    HttpEntity httpEntity = multipartEntityBuilder.build();
    httpPost.setEntity(httpEntity);

    // Set authentication information
    String encodedCredentials = Helper.getEncodedCredentials(FabQRFunctions.getFabqrPrivateUser(),
            FabQRFunctions.getFabqrPrivatePassword());
    if (!encodedCredentials.isEmpty()) {
        httpPost.addHeader("Authorization", "Basic " + encodedCredentials);
    }

    // Send request
    CloseableHttpResponse res = httpClient.execute(httpPost);

    // React to possible server side errors
    if (res.getStatusLine() == null || res.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new Exception("FabQR upload exception: Server sent wrong HTTP status code: "
                + new Integer(res.getStatusLine().getStatusCode()).toString());
    }

    // Close everything correctly
    res.close();
    httpClient.close();
}

From source file:com.calmio.calm.integration.Helpers.HTTPHandler.java

public static HTTPResponseData sendPost(String url, String body, String username, String pwd) throws Exception {

    CloseableHttpClient client = HttpClients.custom()
            .setDefaultCredentialsProvider(getCredentialsProvider(url, username, pwd)).build();

    int responseCode = 0;
    StringBuffer respo = null;/*from  w  ww .  ja va 2 s .  c  om*/
    String userPassword = username + ":" + pwd;
    //        String encoding = Base64.getEncoder().encodeToString(userPassword.getBytes());
    String encoding = Base64.encodeBase64String(userPassword.getBytes());

    try {
        HttpPost request = new HttpPost(url);
        request.addHeader("Authorization", "Basic " + encoding);
        request.addHeader("User-Agent", USER_AGENT);
        request.addHeader("Accept-Language", "en-US,en;q=0.5");
        request.addHeader("Content-Type", "application/json; charset=UTF-8");
        request.setHeader("Accept", "application/json");
        System.out.println("Executing request " + request.getRequestLine());
        System.out.println("Executing request " + Arrays.toString(request.getAllHeaders()));
        StringEntity se = new StringEntity(body);
        request.setEntity(se);
        CloseableHttpResponse response = client.execute(request);
        try {
            responseCode = response.getStatusLine().getStatusCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post body : " + body);
            System.out.println("Response Code : " + responseCode);
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            respo = new StringBuffer();
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                respo.append(inputLine);
            }
        } finally {
            response.close();
        }
    } finally {
        client.close();
    }

    HTTPResponseData result = new HTTPResponseData(responseCode, ((respo == null) ? "" : respo.toString()));
    System.out.println(result.getStatusCode() + "/n" + result.getBody());
    return result;
}

From source file:com.econcept.pingconnectionutility.utility.PingConnectionUtility.java

private static void httpPingable(String targetURI) throws IOException, URISyntaxException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet();
    httpGet.setURI(new URI(targetURI));
    CloseableHttpResponse response = httpClient.execute(httpGet);

    int currentCode = response.getStatusLine().getStatusCode();
    try {//from ww w. j a  v  a  2  s  . c  o  m

        if (currentCode >= 200 && currentCode < 300) {
            HttpEntity entity = response.getEntity();

            InputStream responseStream = entity.getContent();

            StringWriter writer = new StringWriter();

            IOUtils.copy(responseStream, writer, "UTF-8");

            System.out.println("Target Server are ok: " + currentCode);
            System.out.println(writer.toString());

            EntityUtils.consume(entity);
        } // if
        else {
            System.out.println("Target Server are not ok: " + currentCode);
        } // else
    } // try
    finally {
        response.close();
    } // finally

}

From source file:com.magnet.tools.tests.RestStepDefs.java

@When("^I send the following Rest queries:$")
public static void sendRestQueries(List<RestQueryEntry> entries) throws Throwable {
    for (RestQueryEntry e : entries) {
        String url = expandVariables(e.url);
        StatusLine statusLine;//from  w  ww  .  j ava  2  s. c o  m
        HttpUriRequest httpRequest;
        HttpEntity entityResponse;
        CloseableHttpClient httpClient = getTestHttpClient(new URI(url));

        Object body = isStringNotEmpty(e.body) ? e.body : getRef(e.bodyRef);

        String verb = e.verb;
        if ("GET".equalsIgnoreCase(verb)) {

            httpRequest = new HttpGet(url);
        } else if ("POST".equalsIgnoreCase(verb)) {
            httpRequest = new HttpPost(url);
            ((HttpPost) httpRequest).setEntity(new StringEntity(expandVariables((String) body)));
        } else if ("PUT".equalsIgnoreCase(verb)) {
            httpRequest = new HttpPut(url);
            ((HttpPut) httpRequest).setEntity(new StringEntity(expandVariables((String) body)));
        } else if ("DELETE".equalsIgnoreCase(verb)) {
            httpRequest = new HttpDelete(url);
        } else {
            throw new IllegalArgumentException("Unknown verb: " + e.verb);
        }
        String response;
        setHttpHeaders(httpRequest, e);
        ScenarioUtils.log("Sending HTTP Request: " + e.url);
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpRequest);
            statusLine = httpResponse.getStatusLine();
            entityResponse = httpResponse.getEntity();
            InputStream is = entityResponse.getContent();
            response = IOUtils.toString(is);
            EntityUtils.consume(entityResponse);
        } finally {
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (Exception ex) {
                    /* do nothing */ }
            }
        }

        ScenarioUtils.log("====> Received response body:\n " + response);
        Assert.assertNotNull(response);
        setHttpResponseBody(response);
        if (isStringNotEmpty(e.expectedResponseBody)) { // inline the assertion check on http response body
            ensureHttpResponseBody(e.expectedResponseBody);
        }

        if (isStringNotEmpty(e.expectedResponseBodyRef)) { // inline the assertion check on http response body
            ensureHttpResponseBody((String) getRef(e.expectedResponseBodyRef));
        }

        if (isStringNotEmpty(e.expectedResponseContains)) { // inline the assertion check on http response body
            ensureHttpResponseBodyContains(e.expectedResponseContains);
        }

        if (null == statusLine) {
            throw new IllegalArgumentException("Status line in http response is null, request was " + e.url);
        }

        int statusCode = statusLine.getStatusCode();
        ScenarioUtils.log("====> Received response code: " + statusCode);
        setHttpResponseStatus(statusCode);
        if (isStringNotEmpty(e.expectedResponseStatus)) { // inline the assertion check on http status
            ensureHttpResponseStatus(Integer.parseInt(e.expectedResponseStatus));
        }

    }

}

From source file:com.hy.utils.pay.wx.ClientCustomSSL.java

public static void test() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("D:/10016225.p12"));
    try {//from   w  w w .  j av a  2 s  .  c om
        keyStore.load(instream, "10016225".toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "10016225".toCharArray()).build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");

        System.out.println("executing request" + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                }

            }
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.beginner.core.utils.HttpUtil.java

/**
 * <p>To request the GET way.</p>
 * /* ww w  .  ja v a  2 s .  co  m*/
 * @param url      request URI
 * @param timeout   request timeout time in milliseconds(The default timeout time for 30 seconds.)
 * @return String   response result
 * @throws Exception
 * @since 1.0.0
 */
public static String get(String url, Integer timeout) throws Exception {

    // Validates input
    if (StringUtils.isBlank(url))
        throw new IllegalArgumentException("The url cannot be null and cannot be empty.");

    //The default timeout time for 30 seconds
    if (null == timeout)
        timeout = 30000;

    CloseableHttpClient httpClient = HttpClients.createDefault();

    CloseableHttpResponse httpResponse = null;
    String result = null;

    try {
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).build();

        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);

        httpResponse = httpClient.execute(httpGet);

        HttpEntity entity = httpResponse.getEntity();
        result = EntityUtils.toString(entity);

        EntityUtils.consume(entity);
    } catch (Exception e) {
        logger.error("GET?", e);
        return null;
    } finally {
        if (null != httpResponse)
            httpResponse.close();
        if (null != httpClient)
            httpClient.close();
    }
    return result;
}

From source file:eionet.gdem.utils.HttpUtils.java

/**
 * Method checks whether the resource behind the given URL exist. The method calls HEAD request and if the resonse code is 200,
 * then returns true. If exception is thrown or response code is something else, then the result is false.
 *
 * @param url URL/*from  w w w . j a v  a 2  s  .  c  o m*/
 * @return True if resource behind the url exists.
 */
public static boolean urlExists(String url) {

    CloseableHttpClient client = HttpClients.createDefault();

    // Create a method instance.
    HttpHead method = new HttpHead(url);
    CloseableHttpResponse response = null;
    try {
        // Execute the method.
        response = client.execute(method);
        int statusCode = response.getStatusLine().getStatusCode();
        return statusCode == HttpStatus.SC_OK;
        /*} catch (HttpException e) {
            LOGGER.error("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
            return false;*/
    } catch (IOException e) {
        LOGGER.error("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        return false;
    } finally {
        // Release the connection.
        method.releaseConnection();
        try {
            response.close();
        } catch (IOException e) {
            // do nothing
        }
    }
}

From source file:org.wuspba.ctams.ws.ITBandContestEntryController.java

protected static void delete() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("id", TestFixture.INSTANCE.bandContestEntry.getId()).build();

    HttpDelete httpDelete = new HttpDelete(uri);

    CloseableHttpResponse response = null;

    try {//from   ww  w.j  a va2 s. c  o m
        response = httpclient.execute(httpDelete);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }

    ITBandContestController.delete();
    ITBandController.delete();
    ITVenueController.delete();
    ITJudgeController.delete();
}

From source file:org.wuspba.ctams.ws.ITSoloContestEntryController.java

protected static void delete() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("id", TestFixture.INSTANCE.soloContestEntry.getId()).build();

    HttpDelete httpDelete = new HttpDelete(uri);

    CloseableHttpResponse response = null;

    try {//from   www  .ja  v  a  2 s  . c  om
        response = httpclient.execute(httpDelete);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }

    ITSoloContestController.delete();
    ITPersonController.delete();
    ITVenueController.delete();
    ITJudgeController.delete();
}

From source file:com.networknt.light.server.handler.loader.PageLoader.java

private static void loadPageFile(String host, File file) {
    Scanner scan = null;/*from w  ww.java 2 s  .  c o  m*/
    try {
        scan = new Scanner(file, Loader.encoding);
        // the content is only the data portion. convert to map
        String content = scan.useDelimiter("\\Z").next();
        String pageId = file.getName();
        pageId = pageId.substring(0, pageId.lastIndexOf('.'));
        if (content != null && !content.equals(pageMap.get(pageId))) {
            System.out.println(content);
            System.out.println(pageMap.get(pageId));
            Map<String, Object> inputMap = new HashMap<String, Object>();
            inputMap.put("category", "page");
            inputMap.put("name", "impPage");
            inputMap.put("readOnly", false);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("pageId", pageId);
            data.put("content", content);
            inputMap.put("data", data);
            HttpPost httpPost = new HttpPost(host + "/api/rs");
            httpPost.addHeader("Authorization", "Bearer " + jwt);
            StringEntity input = new StringEntity(
                    ServiceLocator.getInstance().getMapper().writeValueAsString(inputMap));
            input.setContentType("application/json");
            httpPost.setEntity(input);
            CloseableHttpResponse response = httpclient.execute(httpPost);

            try {
                System.out.println("Page: " + file.getAbsolutePath() + " is loaded with status "
                        + response.getStatusLine());
                HttpEntity entity = response.getEntity();
                BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
                String json = "";
                String line = "";
                while ((line = rd.readLine()) != null) {
                    json = json + line;
                }
                //System.out.println("json = " + json);
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } else {
            //System.out.println("Skip file " + pageId);
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        if (scan != null)
            scan.close();
    }
}