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

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

Introduction

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

Prototype

public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException 

Source Link

Usage

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

/**
 * Downloads remote file//from   w w w.  j av a  2s .c o m
 * @param url URL
 * @return Downloaded file
 * @throws DCMException If an error occurs.
 * @throws IOException If an error occurs.
 */
public static byte[] downloadRemoteFile(String url) throws DCMException, IOException {
    byte[] responseBody = null;
    CloseableHttpClient client = HttpClients.createDefault();

    // Create a method instance.
    HttpGet method = new HttpGet(url);
    // Execute the method.
    CloseableHttpResponse response = null;
    try {
        response = client.execute(method);
        HttpEntity entity = response.getEntity();
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode != HttpStatus.SC_OK) {
            LOGGER.error("Method failed: " + response.getStatusLine().getReasonPhrase());
            throw new DCMException(BusinessConstants.EXCEPTION_SCHEMAOPEN_ERROR,
                    response.getStatusLine().getReasonPhrase());
        }

        // Read the response body.
        InputStream instream = entity.getContent();
        responseBody = IOUtils.toByteArray(instream);

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        // System.out.println(new String(responseBody));
        /*catch (HttpException e) {
        LOGGER.error("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
        throw e;*/
    } catch (IOException e) {
        LOGGER.error("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        throw e;
    } finally {
        // Release the connection.
        response.close();
        method.releaseConnection();
        client.close();
    }
    return responseBody;
}

From source file:com.sugarcrm.candybean.webservices.WS.java

/**
 * Protected method to handle sending and receiving an http request
 *
 * @param request The Http request that is being send
 * @param headers Map of Key Value header pairs
 * @return Key Value pairs of the response
 * @throws CandybeanException If the response is null or not an acceptable HTTP code
 *//*  w ww. ja  va  2 s.c om*/
protected static Map<String, Object> handleRequest(HttpUriRequest request, Map<String, String> headers)
        throws CandybeanException {
    // Add the request headers and execute the request
    for (Map.Entry<String, String> header : headers.entrySet()) {
        request.addHeader(new BasicHeader(header.getKey(), header.getValue()));
    }
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    try {
        HttpResponse response = httpClient.execute(request);

        // Check for invalid responses or error return codes
        if (response == null) {
            throw new CandybeanException("Http Request failed: Response null");
        }

        // Cast the response into a Map and return
        JSONObject parse = (JSONObject) JSONValue
                .parse(new InputStreamReader(response.getEntity().getContent()));
        @SuppressWarnings("unchecked")
        Map<String, Object> mapParse = (Map<String, Object>) parse;

        int code = response.getStatusLine().getStatusCode();
        if (!ACCEPTABLE_RETURN_CODE_SET.contains(code)) {
            throw new CandybeanException(
                    "HTTP request received HTTP code: " + code + "\n" + "Response: " + response.toString());
        } else if (mapParse == null) {
            throw new CandybeanException("Could not format response\n" + "Response: " + response.toString());
        }

        return mapParse;
    } catch (IOException | IllegalStateException e) {
        // Cast the other possible exceptions as a CandybeanException
        throw new CandybeanException(e);
    }
}

From source file:net.wedjaa.elasticparser.tester.ESSearchTester.java

private static void populateTest() {
    // Get the bulk index as a stream
    InputStream bulkStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("bulk-insert.json");
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();

    HttpResponse response;/*from w ww . ja  va 2  s.  c o  m*/
    // Drop the index if it's there
    HttpDelete httpdelete = new HttpDelete("http://localhost:9500/unit");
    try {
        response = httpclient.execute(httpdelete);
        System.out.println("Index Deleted: " + response);
        httpclient.close();
    } catch (ClientProtocolException protoException) {
        System.err.println("Protocol Error while deleting index: " + protoException);
    } catch (IOException ioException) {
        System.err.println("IO Error while deleting index: " + ioException);
    }

    HttpPost httppost = new HttpPost("http://localhost:9500/_bulk");

    InputStreamEntity isEntity = new InputStreamEntity(bulkStream);
    httppost.setEntity(isEntity);

    try {
        httpclient = HttpClientBuilder.create().build();
        response = httpclient.execute(httppost);
        System.out.println(response.getStatusLine());
        httpclient.close();
    } catch (ClientProtocolException protoException) {
        System.err.println("Protocol Error while bulk indexing: " + protoException);
    } catch (IOException ioException) {
        System.err.println("IO Error while bulk indexing: " + ioException);
    }
    System.out.println("Waiting for index to settle down...");
    while (countIndexed() < 50) {
        System.out.println("...");
    }
    System.out.println("...done!");
}

From source file:org.keycloak.testsuite.util.URLAssert.java

public static void assertGetURL(URI url, String accessToken, AssertResponseHandler handler) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*w w w.j  a  v a  2  s  . c  o m*/
        HttpGet get = new HttpGet(url);
        get.setHeader("Authorization", "Bearer " + accessToken);

        CloseableHttpResponse response = httpclient.execute(get);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Response status error: " + response.getStatusLine().getStatusCode() + ": " + url);
        }

        handler.assertResponse(response);

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.twinsoft.convertigo.engine.util.HttpUtils.java

public static JSONObject requestToJSON(CloseableHttpClient httpClient, HttpRequestBase request)
        throws ClientProtocolException, IOException, UnsupportedOperationException, JSONException {
    CloseableHttpResponse response = httpClient.execute(request);
    HttpEntity responseEntity = response.getEntity();
    ContentTypeDecoder contentType = new ContentTypeDecoder(
            responseEntity == null || responseEntity.getContentType() == null ? ""
                    : responseEntity.getContentType().getValue());
    JSONObject json = new JSONObject(
            IOUtils.toString(responseEntity.getContent(), contentType.charset("UTF-8")));
    return json;/*  w  ww  .j  a  va 2s. co  m*/
}

From source file:httpServerClient.app.QuickStart.java

public static void getAllMessages(String[] args) throws Exception {
    // arguments to run Quick start:
    // args[0] GET
    // args[1] IPAddress of server
    // args[2] port No.

    CloseableHttpClient httpclient = HttpClients.createDefault();
    JacksonObjectMapperToList myList = new JacksonObjectMapperToList();

    try {/*from  www.java 2  s . c  o  m*/
        HttpGet httpGet = new HttpGet("http://" + args[1] + ":" + args[2] + "/getAllMessages");
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        // The underlying HTTP connection is still held by the response
        // object
        // to allow the response content to be streamed directly from the
        // network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally
        // clause.
        // Please note that if response content is not fully consumed the
        // underlying
        // connection cannot be safely re-used and will be shut down and
        // discarded
        // by the connection manager.
        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            String result = EntityUtils.toString(entity1);

            /*
             * Vypisanie odpovede do konzoly a discard dat zo serveru.
             */
            //myList.jsonToList(result);
            myList.jacksonToList(result);
            myList.PrintList();
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }

    } finally {
        httpclient.close();
    }
}

From source file:org.epics.archiverappliance.retrieval.channelarchiver.XMLRPCClient.java

/**
 * Internal method to make a XML_RPC post call and call the SAX handler on the returned document.
 * @param serverURL The Server URL/*from  w ww . j a v a2  s . c  om*/
 * @param handler  DefaultHandler 
 * @param postEntity StringEntity 
 * @throws IOException  &emsp; 
 * @throws SAXException  &emsp; 
 */
private static void doHTTPPostAndCallSAXHandler(String serverURL, DefaultHandler handler,
        StringEntity postEntity) throws IOException, SAXException {
    logger.debug("Executing doHTTPPostAndCallSAXHandler with the server URL " + serverURL);
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost postMethod = new HttpPost(serverURL);
    postMethod.addHeader("Content-Type", "text/xml");
    postMethod.setEntity(postEntity);
    logger.debug("Executing the HTTP POST" + serverURL);
    HttpResponse response = httpclient.execute(postMethod);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        logger.debug("Obtained a HTTP entity of length " + entity.getContentLength());
        try (InputStream is = entity.getContent()) {
            SAXParserFactory sfac = SAXParserFactory.newInstance();
            sfac.setNamespaceAware(false);
            sfac.setValidating(false);
            SAXParser parser = sfac.newSAXParser();
            parser.parse(is, handler);
        } catch (ParserConfigurationException pex) {
            throw new IOException(pex);
        }
    } else {
        throw new IOException("HTTP response did not have an entity associated with it");
    }
}

From source file:org.openo.nfvo.emsdriver.northbound.client.HttpClientUtil.java

public static String doGet(String url, String charset) {
    CloseableHttpClient httpClient = null;
    HttpGet httpGet = null;/*  ww  w.j  av  a  2  s. com*/
    String result = null;
    try {
        httpClient = HttpClientFactory.getSSLClientFactory();
        httpGet = new HttpGet(url);

        CloseableHttpResponse response = httpClient.execute(httpGet);

        try {
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception e) {
            log.error("", e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
    } catch (Exception e) {
        log.error("doGet is fail ", e);
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
            }
        }
    }
    return result;
}

From source file:org.openo.nfvo.emsdriver.northbound.client.HttpClientUtil.java

public static String doDelete(String url, String charset) {
    CloseableHttpClient httpClient = null;
    HttpDelete httpDelete = null;//from  w w  w  .  ja va 2  s  . co  m
    String result = null;
    try {
        httpClient = HttpClientFactory.getSSLClientFactory();
        httpDelete = new HttpDelete(url);

        CloseableHttpResponse response = httpClient.execute(httpDelete);

        try {
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception e) {
            log.error("", e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
    } catch (Exception e) {
        log.error("doDelete is fail ", e);
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
            }
        }
    }
    return result;
}

From source file:shootersubdownloader.Shootersubdownloader.java

private static void down(File f) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String url = String.format("https://www.shooter.cn/api/subapi.php?filehash=%s&pathinfo=%s&format=json",
            computefilehash(f), f.getName());
    System.out.println(url);/*from w  w w  . ja va  2  s.co m*/
    HttpGet request = new HttpGet(url);
    CloseableHttpResponse r = httpclient.execute(request);
    System.out.println(r.getStatusLine());
    HttpEntity e = r.getEntity();
    String s = EntityUtils.toString(e);
    System.out.println(s);
    JSONArray json = JSONArray.fromObject(s);
    //        JSONObject json = JSONObject.fromObject(s);
    System.out.println(json.size());
    for (int i = 0; i < json.size(); i++) {
        System.out.println(i);
        JSONObject obj = json.getJSONObject(i);
        JSONArray fs = obj.getJSONArray("Files");
        String downurl = fs.getJSONObject(0).getString("Link");
        HttpGet r2 = new HttpGet(downurl);
        CloseableHttpResponse res2 = httpclient.execute(r2);
        //            Header[] headers = res2.getAllHeaders();
        //            for(Header h:headers){
        //                System.out.println(h.getName());
        //                System.out.println(h.getValue());
        //            }
        Header header = res2.getFirstHeader("Content-Disposition");
        String sig = "filename=";
        String v = header.getValue();
        String fn = v.substring(v.indexOf(sig) + sig.length());
        HttpEntity e2 = res2.getEntity();
        File outf = new File(fn);
        FileOutputStream fos = new FileOutputStream(outf);
        e2.writeTo(fos);

        System.out.println(filecharsetdetect.FileCharsetDetect.detect(outf));
        //            res2.getEntity().writeTo(new FileOutputStream(fn));
        System.out.println(fn);
        res2.close();
    }

    r.close();
    httpclient.close();
}