Example usage for org.apache.http.impl.client HttpClients createDefault

List of usage examples for org.apache.http.impl.client HttpClients createDefault

Introduction

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

Prototype

public static CloseableHttpClient createDefault() 

Source Link

Document

Creates CloseableHttpClient instance with default configuration.

Usage

From source file:goofyhts.torrentkinesis.test.HttpTest.java

@Test
public void testGet() {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpClientContext context = new HttpClientContext();
        CredentialsProvider credProv = new BasicCredentialsProvider();
        credProv.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("root", "Whcinhry21#"));
        context.setCredentialsProvider(credProv);
        HttpGet httpGet = new HttpGet("http://localhost:8150/gui/token.html");

        CloseableHttpResponse response = client.execute(httpGet, context);
        String responseBody = IOUtils.toString(response.getEntity().getContent());
        System.out.println(responseBody);
        Document doc = Jsoup.parse(responseBody);
        System.out.println(doc.getElementById("token").text());
    } catch (ClientProtocolException e) {
        e.printStackTrace();/* ww  w. ja v  a2 s .  c  o  m*/
    } catch (IOException e) {
        e.printStackTrace();
    }
    //Assert.assertTrue(true);
}

From source file:ee.ria.xroad.common.util.healthcheck.MaintenanceModeTest.java

/**
 * Setup for all tests/*from  w w w  . j  a  v  a2  s  .c  o m*/
 * @throws Exception throws an Exception if unable to setup
 */
@BeforeClass
public static void setUpBeforeClass() throws Exception {
    URI healthCheckURI = new URIBuilder().setScheme("http").setHost("localhost").setPort(TEST_PORT_NUMBER)
            .build();

    healthCheckGet = new HttpGet(healthCheckURI);
    testClient = HttpClients.createDefault();

    testProvider = mock(StoppableCombinationHealthCheckProvider.class);
    testPort = new HealthCheckPort(testProvider, TEST_PORT_NUMBER);
    testPort.start();
}

From source file:com.oakhole.voa.utils.HttpClientUtils.java

/**
 * ???map/*from   ww  w .j a va2  s.co m*/
 *
 * @param uri
 * @return
 */
public static HttpEntity get(String uri) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(uri);
    try {
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        return httpResponse.getEntity();
    } catch (IOException e) {
        logger.error(":{}", e.getMessage());
    }
    return null;
}

From source file:cn.aofeng.demo.httpclient.HttpClientBasic.java

public void post() throws ClientProtocolException, IOException {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("chinese", ""));
    params.add(new BasicNameValuePair("english", ""));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, _charset);

    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(_targetHost + "/post");
    post.addHeader("Cookie", "character=abcdefghijklmnopqrstuvwxyz; sign=abc-123-jkl-098");
    post.setEntity(entity);/* ww w .  j  av  a  2  s .c om*/
    CloseableHttpResponse response = client.execute(post);
    processResponse(response);
}

From source file:eu.matejkormuth.crawler2.PageFetcher.java

/**
 * Creates a new PageFetcher instance using Apache commons-io library
 * HttpClient./*from   w w  w  .ja  v  a2  s. c om*/
 */
public PageFetcher() {
    this.client = HttpClients.createDefault();
    this.responseHandler = new DefaultResponseHandler();
}

From source file:com.ibm.watson.app.common.util.rest.SimpleRestClient.java

public SimpleRestClient(String url) {
    this(url, HttpClients.createDefault());
}

From source file:cz.muni.fi.webmias.TeXConverter.java

/**
 * Converts TeX formula to MathML using LaTeXML through a web service.
 *
 * @param query String containing one or more keywords and TeX formulae
 * (formulae enclosed in $ or $$).// w  ww  .j a va  2 s  .  c  om
 * @return String containing formulae converted to MathML that replaced
 * original TeX forms. Non math tokens are connected at the end.
 */
public static String convertTexLatexML(String query) {
    query = query.replaceAll("\\$\\$", "\\$");
    if (query.matches(".*\\$.+\\$.*")) {
        try {
            HttpClient httpclient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(LATEX_TO_XHTML_CONVERSION_WS_URL);

            // Request parameters and other properties.
            List<NameValuePair> params = new ArrayList<>(1);
            params.add(new BasicNameValuePair("code", query));
            httppost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            // Execute and get the response.
            HttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    try (InputStream responseContents = resEntity.getContent()) {
                        DocumentBuilder dBuilder = MIaSUtils.prepareDocumentBuilder();
                        org.w3c.dom.Document doc = dBuilder.parse(responseContents);
                        NodeList ps = doc.getElementsByTagName("p");
                        String convertedMath = "";
                        for (int k = 0; k < ps.getLength(); k++) {
                            Node p = ps.item(k);
                            NodeList pContents = p.getChildNodes();
                            for (int j = 0; j < pContents.getLength(); j++) {
                                Node pContent = pContents.item(j);
                                if (pContent instanceof Text) {
                                    convertedMath += pContent.getNodeValue() + "\n";
                                } else {
                                    TransformerFactory transFactory = TransformerFactory.newInstance();
                                    Transformer transformer = transFactory.newTransformer();
                                    StringWriter buffer = new StringWriter();
                                    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                                    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                    transformer.transform(new DOMSource(pContent), new StreamResult(buffer));
                                    convertedMath += buffer.toString() + "\n";
                                }
                            }
                        }
                        return convertedMath;
                    }
                }
            }

        } catch (TransformerException | SAXException | ParserConfigurationException | IOException ex) {
            Logger.getLogger(ProcessServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return query;
}

From source file:com.dgpx.web.BaiduTTSBean.java

private void initAccessToken() throws IOException {

    StringBuilder sb = new StringBuilder();
    sb.append("https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials");
    sb.append("&");
    sb.append("client_id=HI1vugSyWg0Gc2GR4RSj2Gwj");
    sb.append("&");
    sb.append("client_secret=ff1aed14438e930fc9a5abb2a14a1714");
    sb.append("&");

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(sb.toString());
    CloseableHttpResponse response = httpclient.execute(httpGet);
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_OK) {
        e = Calendar.getInstance();
        try {/*from   w w  w  .ja v  a2s . c o  m*/
            HttpEntity entity = response.getEntity();
            JSONObject resultJsonObject = null;
            try {
                resultJsonObject = new JSONObject(EntityUtils.toString(entity, "UTF-8"));
                access_token = resultJsonObject.getString("access_token");
                expires_in = Integer.parseInt(resultJsonObject.get("expires_in").toString());
                e.add(Calendar.SECOND, expires_in);
            } catch (IOException | ParseException | JSONException ex) {
                Logger.getLogger(BaiduTTSBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        } finally {
            response.close();
        }
    }

}

From source file:co.paralleluniverse.fibers.retrofit.FiberRestAdapterBuilderTest.java

public static void waitUrlAvailable(final String url) throws InterruptedException, IOException {
    for (;;) {//from   w w  w  . j  a v  a  2  s.  c  om
        Thread.sleep(10);
        try {
            if (HttpClients.createDefault().execute(new HttpGet(url)).getStatusLine().getStatusCode() > -100)
                break;
        } catch (HttpHostConnectException ex) {
        }
    }
}

From source file:net.palette_software.pet.restart.HelperHttpClient.java

static void modifyWorker(String targetURL, BalancerManagerManagedWorker w, HashMap<String, Integer> switches,
        int simulation) throws Exception {
    try (CloseableHttpClient client = HttpClients.createDefault()) {

        if (!(simulation < 1)) {
            return;
        }//from  ww w  .j  a  v  a  2  s.c  om

        //connect to Balancer Manager
        HttpPost httpPost = new HttpPost(targetURL);

        List<NameValuePair> params = new ArrayList<>();

        //check the switches map for the keys are acceptable to interact with Balancer Manager
        for (Map.Entry<String, Integer> entry : switches.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue().toString();
            if (!BalancerManagerAcceptedPostKeysContains(key)) {
                HelperLogger.loggerStdOut.info("Bad key in modifyWorker (" + key + "," + value + ")");
                continue;
            }
            params.add(new BasicNameValuePair(key, value));
        }

        //add the necessary parameters
        params.add(new BasicNameValuePair("b", w.getBalancerMemberName()));
        params.add(new BasicNameValuePair("w", w.getName()));
        params.add(new BasicNameValuePair("nonce", w.getNonce()));
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        //send the request
        CloseableHttpResponse response = client.execute(httpPost);

        //throw an exception is the result status is abnormal.
        int responseCode = response.getStatusLine().getStatusCode();
        if (200 != responseCode) {
            throw new Exception("Balancer-manager returned a http response of " + responseCode);
        }
    }
}