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:cn.jumper.study.http.ClientFormLogin.java

public static void main(String[] args) throws Exception {
    BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

    HttpHost proxy = new HttpHost("192.168.10.3", 8080, "http");

    RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

    try {/* w  w  w .  j  ava  2s. com*/
        HttpGet httpget = new HttpGet("http://www.ksf-food.com/admin/Login.asp");
        httpget.setConfig(config);
        CloseableHttpResponse response1 = httpclient.execute(httpget);
        try {
            HttpEntity entity = response1.getEntity();

            System.out.println("Login form get: " + response1.getStatusLine());
            EntityUtils.consume(entity);

            System.out.println("Initial set of cookies:");
            List<Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        } finally {
            response1.close();
        }

        String code = "";
        try {
            HttpUriRequest httpgetCode = RequestBuilder.get()
                    .setUri("http://www.ksf-food.com/admin/inc/checkcode.asp").setConfig(config).build();

            /*
             * HttpGet httpgetCode = new HttpGet(
             * "http://www.qufuev.com/admin/inc/checkcode.asp");
             * httpgetCode.setConfig(config);
             */

            System.out.println("Executing request " + httpgetCode.getRequestLine());
            System.out.println("========================================================");
            System.out.println("==httpget header ==");
            for (Header header : httpgetCode.getAllHeaders()) {
                System.out.println(header.getName() + ":" + header.getValue());
            }
            System.out.println("==httpget header ==");

            ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
                public String handleResponse(final HttpResponse response)
                        throws ClientProtocolException, IOException {
                    int status = response.getStatusLine().getStatusCode();
                    if (status >= 200 && status < 300) {
                        HttpEntity entity = response.getEntity();
                        System.out.println("==respons header ==");
                        for (Header header : response.getAllHeaders()) {
                            System.out.println(header.getName() + ":" + header.getValue());
                        }
                        System.out.println("==respons header ==");
                        String fileName = System.currentTimeMillis() + "";
                        DataOutputStream dataOutputStream = new DataOutputStream(
                                new FileOutputStream("d://test//e3//" + fileName + ".jpg"));
                        dataOutputStream.write(EntityUtils.toByteArray(entity));
                        dataOutputStream.close();
                        return ImageTest.getAllOcr("d://test//e3//" + fileName + ".jpg");
                    } else {
                        throw new ClientProtocolException("Unexpected response status: " + status);
                    }
                }

            };
            code = httpclient.execute(httpgetCode, responseHandler);
            System.out.println("ClientFormLogin.main()-CheckCode:" + code);
            System.out.println("----------------------------------------");
        } catch (IOException e) {
            e.printStackTrace();
        }

        HttpUriRequest login = RequestBuilder.post()
                .setUri(new URI("http://www.ksf-food.com/admin/Admin_ChkLogin.asp"))
                .addParameter("UserName", "username").addParameter("Password", "password")
                .addParameter("CheckCode", code).setConfig(config).build();

        System.out.println("========================================================");
        System.out.println("==httpget header ==");
        for (Header header : login.getAllHeaders()) {
            System.out.println(header.getName() + ":" + header.getValue());
        }

        CloseableHttpResponse response2 = httpclient.execute(login);
        try {
            HttpEntity entity = response2.getEntity();

            System.out.println("Login form post: " + response2.getStatusLine());
            // EntityUtils.consume(entity);
            System.out.println("ClientFormLogin.main():\\n" + EntityUtils.toString(entity, "GBK"));

            System.out.println("Post logon cookies:");
            List<Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        } finally {
            response2.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:client.QueryLastFm.java

License:asdf

public static void main(String[] args) throws Exception {

    // isAlreadyInserted("asdfs","jas,jnjkah");

    // FileWriter fw = new FileWriter(".\\tracks.csv");
    OutputStream track_os = new FileOutputStream(".\\tracks.csv");
    PrintWriter out = new PrintWriter(new OutputStreamWriter(track_os, "UTF-8"));

    OutputStream track_id_os = new FileOutputStream(".\\track_id_sim_track_id.csv");
    PrintWriter track_id_out = new PrintWriter(new OutputStreamWriter(track_id_os, "UTF-8"));

    track_id_out.print("");

    ByteArrayInputStream input;/*from   ww  w.  jav a  2 s .c  o m*/
    Document doc = null;
    CloseableHttpClient httpclient = HttpClients.createDefault();

    String trackName = "";
    String artistName = "";
    String sourceMbid = "";
    out.print("ID");// first row first column
    out.print(",");
    out.print("TrackName");// first row second column
    out.print(",");
    out.println("Artist");// first row third column

    track_id_out.print("source");// first row second column
    track_id_out.print(",");
    track_id_out.println("target");// first row third column
    // track_id_out.print(",");
    // track_id_out.println("type");// first row third column

    // out.flush();

    // out.close();

    // fw.close();

    // os.close();

    try {
        URI uri = new URIBuilder().setScheme("http").setHost("ws.audioscrobbler.com").setPath("/2.0/")
                .setParameter("method", "track.getsimilar").setParameter("artist", "cher")
                .setParameter("track", "believe").setParameter("limit", "100")
                .setParameter("api_key", "88858618961414f8bec919bddd057044").build();

        // new URIBuilder().
        HttpGet request = new HttpGet(uri);

        // request.
        // This is useful for last.fm logging and preventing them from blocking this client
        request.setHeader(HttpHeaders.USER_AGENT,
                "nileshmore@gatech.edu - ClassAssignment at GeorgiaTech Non-commercial use");

        HttpGet httpGet = new HttpGet(
                "http://ws.audioscrobbler.com/2.0/?method=track.getsimilar&artist=cher&track=believe&limit=4&api_key=88858618961414f8bec919bddd057044");
        CloseableHttpResponse response = httpclient.execute(request);

        int statusCode = response.getStatusLine().getStatusCode();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        // 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 {
            if (statusCode == 200) {
                HttpEntity entity1 = response.getEntity();
                BufferedReader br = new BufferedReader(
                        new InputStreamReader((response.getEntity().getContent())));
                Document document = builder.parse((response.getEntity().getContent()));
                Element root = document.getDocumentElement();
                root.normalize();
                // Need to focus and resolve this part
                NodeList nodes;
                nodes = root.getChildNodes();

                nodes = root.getElementsByTagName("track");
                if (nodes.getLength() == 0) {
                    // System.out.println("empty");
                    return;
                }
                Node trackNode;
                for (int k = 0; k < nodes.getLength(); k++) // can access all tracks now
                {
                    trackNode = nodes.item(k);
                    NodeList trackAttributes = trackNode.getChildNodes();

                    // check if mbid is present in track attributes
                    // System.out.println("Length  " + (trackAttributes.item(5).getNodeName().compareToIgnoreCase("mbid") == 0));

                    if ((trackAttributes.item(5).getNodeName().compareToIgnoreCase("mbid") == 0)) {
                        if (((Element) trackAttributes.item(5)).hasChildNodes())
                            ;// System.out.println("Go aHead");
                        else
                            continue;
                    } else
                        continue;

                    for (int n = 0; n < trackAttributes.getLength(); n++) {
                        Node attribute = trackAttributes.item(n);
                        if ((attribute.getNodeName().compareToIgnoreCase("name")) == 0) {
                            // System.out.println(((Element)attribute).getFirstChild().getNodeValue());
                            trackName = ((Element) attribute).getFirstChild().getNodeValue(); // make string encoding as UTF-8 ************ 

                        }

                        if ((attribute.getNodeName().compareToIgnoreCase("mbid")) == 0) {
                            // System.out.println(n +  "   " +  ((Element)attribute).getFirstChild().getNodeValue());
                            sourceMbid = attribute.getFirstChild().getNodeValue();

                        }

                        if ((attribute.getNodeName().compareToIgnoreCase("artist")) == 0) {
                            NodeList ArtistNodeList = attribute.getChildNodes();
                            for (int j = 0; j < ArtistNodeList.getLength(); j++) {
                                Node Artistnode = ArtistNodeList.item(j);
                                if ((Artistnode.getNodeName().compareToIgnoreCase("name")) == 0) {
                                    // System.out.println(((Element)Artistnode).getFirstChild().getNodeValue());
                                    artistName = ((Element) Artistnode).getFirstChild().getNodeValue();
                                }
                            }
                        }
                    }
                    out.print(sourceMbid);
                    out.print(",");
                    out.print(trackName);
                    out.print(",");
                    out.println(artistName);
                    // out.print(",");
                    findSimilarTracks(track_id_out, sourceMbid, trackName, artistName);

                }
                track_id_out.flush();

                out.flush();
                out.close();
                track_id_out.close();
                track_os.close();

                // fw.close();
                Element trac = (Element) nodes.item(0);
                // trac.normalize();
                nodes = trac.getChildNodes();
                // System.out.println(nodes.getLength());

                for (int i = 0; i < nodes.getLength(); i++) {
                    Node node = nodes.item(i);
                    // System.out.println(node.getNodeName());
                    if ((node.getNodeName().compareToIgnoreCase("name")) == 0) {
                        // System.out.println(((Element)node).getFirstChild().getNodeValue());
                    }

                    if ((node.getNodeName().compareToIgnoreCase("mbid")) == 0) {
                        // System.out.println(((Element)node).getFirstChild().getNodeValue());
                    }

                    if ((node.getNodeName().compareToIgnoreCase("artist")) == 0) {

                        // System.out.println("Well");
                        NodeList ArtistNodeList = node.getChildNodes();
                        for (int j = 0; j < ArtistNodeList.getLength(); j++) {
                            Node Artistnode = ArtistNodeList.item(j);
                            if ((Artistnode.getNodeName().compareToIgnoreCase("name")) == 0) {
                                /* System.out.println(((Element)Artistnode).getFirstChild().getNodeValue());*/
                            }
                            /*System.out.println(Artistnode.getNodeName());*/
                        }
                    }

                }
                /*if(node instanceof Element){
                  //a child element to process
                  Element child = (Element) node;
                  String attribute = child.getAttribute("width");
                }*/

                // System.out.println(root.getAttribute("status"));
                NodeList tracks = root.getElementsByTagName("track");
                Element track = (Element) tracks.item(0);
                // System.out.println(track.getTagName());
                track.getChildNodes();

            } else {
                System.out.println("failed with status" + response.getStatusLine());
            }
            // input = (ByteArrayInputStream)entity1.getContent();
            // do something useful with the response body
            // and ensure it is fully consumed
        } finally {
            response.close();
        }
    }

    finally {
        System.out.println("Exited succesfully.");
        httpclient.close();

    }
}

From source file:org.mobile.mpos.util.HttpClientHelper.java

private static void close(CloseableHttpClient httpClient) {
    try {//w w w . ja v a2 s  . com
        if (httpClient != null) {
            httpClient.close();
        }
    } catch (IOException e) {
        log.error("close httpClient IOException " + e.getMessage());
    }
}

From source file:org.n52.sos.soe.HttpUtil.java

public static XmlObject executeGetAndParseAsXml(String target) throws IOException, XmlException {
    CloseableHttpClient client = createClient();
    XmlObject xo = XmlObject.Factory.parse(executeGet(target, client));
    client.close();
    return xo;/*from ww w  . ja  v  a 2s.  c  o m*/
}

From source file:org.n52.sos.soe.HttpUtil.java

public static JsonNode executeGetAndParseAsJson(String target) throws IOException, ClientProtocolException {
    CloseableHttpClient client = createClient();
    ObjectMapper mapper = new ObjectMapper();
    JsonNode json = mapper.readTree(executeGet(target, client));
    client.close();
    return json;//from   www .j  a  v  a2s. co  m
}

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

private static void closeHttpClient(CloseableHttpClient httpClient) {
    try {//w  w w  .jav  a 2s  . c o  m
        httpClient.close();
    } catch (IOException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.precioustech.fxtrading.utils.TradingUtils.java

public static void closeSilently(CloseableHttpClient httpClient) {
    if (httpClient == null) {
        return;/* w w w .j av  a  2 s . c  om*/
    }
    try {
        httpClient.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.comcast.viper.hlsparserj.PlaylistFactory.java

/**
 * Factory method to generate playlist object. This method uses a very
 * simple HTTP client to download the URL passed by the playlistURL
 * parameters. This method should not be used for applications that require
 * high-performance, as the HTTP connection management is very basic. If
 * your application has high performance requirements us the parsePlaylist
 * method that takes an InputStream./* w  w  w  .j  a  v  a  2 s  .  c  o  m*/
 *
 * @param playlistVersion version of the playlist (V12 is the default)
 * @param playlistURL URL pointing to a playlist
 * @return parsed playlist
 * @throws IOException on connection and parsing exceptions
 */
public static AbstractPlaylist parsePlaylist(final PlaylistVersion playlistVersion, final URL playlistURL)
        throws IOException {
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient httpClient = builder.build();
    PlaylistParser parser = new PlaylistParser();

    try {
        InputStream playlistStream = getPlaylistInputStream(httpClient, playlistURL);
        parser.parse(playlistStream);
    } finally {
        httpClient.close();
    }

    return getVersionSpecificPlaylist(parser, playlistVersion);
}

From source file:org.smartloli.kafka.eagle.common.util.TestHttpClientUtils.java

/**
 * send & get response result./*from   w  w w . j  a v  a 2s .  c  o m*/
 * 
 * @param httpPost
 */
private static void executeAndGetResponse(HttpPost httpPost) {
    CloseableHttpClient httpClient = HttpClients.custom().build();
    HttpResponse response = null;
    try {
        response = httpClient.execute(httpPost);
        String result = EntityUtils.toString(response.getEntity(), "utf-8");
        LOG.info("dingding server result:" + result);
        httpClient.close();
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

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   www. j  a v a2 s.  co  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!");
}