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:it.cloudicaro.disit.servlet.kb.SparqlProxy.java

private void buildSparqlResponse(HttpServletRequest theReq, HttpServletResponse theResp) throws Exception {
    Date start = new Date();
    HttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = null;//w  w  w .j a  v  a 2 s  .  c om
    HttpResponse response = null;

    String theServerHost = Configuration.getInstance().get("kb.rdf.sparql_endpoint",
            "http://192.168.0.106:8080/openrdf-sesame/repositories/icaro5");
    String query = theReq.getParameter("query");
    String aEncodedQuery = URLEncoder.encode(query, "UTF-8");

    String theReqUrl = theServerHost + "?query=" + aEncodedQuery;
    //System.out.println("request: " + theReqUrl);

    try {
        httpget = new HttpGet(theReqUrl);

        //System.out.println("request header:");
        Enumeration<String> aHeadersEnum = theReq.getHeaderNames();
        while (aHeadersEnum.hasMoreElements()) {
            String aHeaderName = aHeadersEnum.nextElement();
            String aHeaderVal = theReq.getHeader(aHeaderName);
            httpget.setHeader(aHeaderName, aHeaderVal);
            //System.out.println("  "+aHeaderName+": "+aHeaderVal);
        }

        if (log.isDebugEnabled()) {
            log.debug("executing request " + httpget.getURI());
        }

        // Create a response handler
        response = httpclient.execute(httpget);

        //System.out.println("response header:");
        // set the same Headers
        for (Header aHeader : response.getAllHeaders()) {
            if (!aHeader.getName().equals("Transfer-Encoding") || !aHeader.getValue().equals("chunked"))
                theResp.setHeader(aHeader.getName(), aHeader.getValue());
            //System.out.println("  "+aHeader.getName()+": "+aHeader.getValue());
        }

        // set the same locale
        if (response.getLocale() != null)
            theResp.setLocale(response.getLocale());

        // set the content
        theResp.setContentLength((int) response.getEntity().getContentLength());
        theResp.setContentType(response.getEntity().getContentType().getValue());

        // set the same status
        theResp.setStatus(response.getStatusLine().getStatusCode());

        // redirect the output
        InputStream aInStream = null;
        OutputStream aOutStream = null;
        try {
            aInStream = response.getEntity().getContent();
            aOutStream = theResp.getOutputStream();

            byte[] buffer = new byte[1024];
            int r = 0;
            do {
                r = aInStream.read(buffer);
                if (r != -1)
                    aOutStream.write(buffer, 0, r);
            } while (r != -1);
            /*
                    int data = aInStream.read();
                    while (data != -1) {
                      aOutStream.write(data);
                    
                      data = aInStream.read();
                    }
             */
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            if (aInStream != null) {
                aInStream.close();
            }
            if (aOutStream != null) {
                aOutStream.close();
            }
        }
        Date end = new Date();
        System.out.println(start + " SPARQL-PERFORMANCE: " + (end.getTime() - start.getTime()) + "ms " + query);
    } finally {
        httpclient.getConnectionManager().closeExpiredConnections();
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:ru.prbb.activeagent.services.AbstractChecker.java

private CloseableHttpClient createHttpClient() {
    return HttpClients.createDefault();
}

From source file:coyote.dx.web.TestHtmlWorker.java

/**
 * This is a control test to make sure the HTTP server is running and the 
 * test file is accessible//  ww w .j a  va  2s .co  m
 */
@Test
public void baseServerTest() throws ClientProtocolException, IOException {
    CloseableHttpResponse response = null;
    try {
        HttpGet httpGet = new HttpGet("http://localhost:" + port + "/data/test.html");
        httpGet.addHeader("if-none-match", "*");
        CloseableHttpClient httpClient = HttpClients.createDefault();
        response = httpClient.execute(httpGet);
        assertEquals(200, response.getStatusLine().getStatusCode());
    } finally {
        if (response != null) {
            response.close();
        }
    }
}

From source file:com.mycompany.bankinterface.eth.EthereumEidProvider.java

private String sendGetMessage(String location) throws IOException {

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(location);

    try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
        HttpEntity entity = response.getEntity();
        String content = IOUtils.toString(entity.getContent());
        EntityUtils.consume(entity);//from w  ww  . j a v a  2s  .  c  o  m
        return content;
    }

}

From source file:email.mandrill.MandrillApiHandler.java

public static List<Map<String, Object>> getTags() {
    List<Map<String, Object>> mandrillTagList = new ArrayList<>();

    try {/*from  w ww  . j  a  v  a  2 s . c om*/

        HttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("https://mandrillapp.com/api/1.0/tags/list.json");
        URI uri = new URIBuilder(httpGet.getURI()).addParameter("key", SendEmail.MANDRILL_KEY).build();
        logger.info("Getting mandrill tags: " + uri.toString());
        Gson gson = new Gson();
        httpGet.setURI(uri);

        //Execute and get the response.
        HttpResponse response = httpclient.execute(httpGet);
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            String jsonContent = EntityUtils.toString(responseEntity);
            logger.info(jsonContent);
            // Create a Reader from String
            Reader stringReader = new StringReader(jsonContent);

            // Pass the string reader to JsonReader constructor
            JsonReader reader = new JsonReader(stringReader);
            reader.setLenient(true);
            mandrillTagList = gson.fromJson(reader, List.class);

        }

    } catch (URISyntaxException ex) {
        Logger.getLogger(MandrillApiHandler.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(MandrillApiHandler.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(MandrillApiHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return mandrillTagList;
}

From source file:org.jboss.as.test.integration.web.session.SessionPersistenceTestCase.java

@Test
public void testLifeCycle() throws Exception {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpGet get = new HttpGet("http://" + TestSuiteEnvironment.getServerAddress()
                + ":8080/sessionPersistence/SessionPersistenceServlet");
        deployer.deploy("web");
        String result = runGet(get, client);
        assertEquals("0", result);
        result = runGet(get, client);/*w w w. ja v  a 2s. com*/
        assertEquals("1", result);
        result = runGet(get, client);
        assertEquals("2", result);
        deployer.undeploy("web");
        deployer.deploy("web");
        result = runGet(get, client);
        assertEquals("3", result);
        result = runGet(get, client);
        assertEquals("4", result);
    }
}

From source file:cn.edu.pku.lib.dataverse.doi.DataCiteRESTfullClient.java

public DataCiteRESTfullClient(String url, String username, String password) {
    this.url = url;
    try {/*from   w  ww.  jav a 2  s  .c o  m*/
        context = HttpClientContext.create();
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(null, -1),
                new UsernamePasswordCredentials(username, password));
        context.setCredentialsProvider(credsProvider);

        httpClient = HttpClients.createDefault();
    } catch (Exception ioe) {
        close();
        logger.log(Level.SEVERE, "Fail to init Client", ioe);
        throw new RuntimeException("Fail to init Client", ioe);
    }
}

From source file:ld.ldhomework.crawler.DownloadTask.java

/**
 * Construct a new {@link DownloadTask} set for a specified uri.
 * //ww w.  j  a va 2  s.  c  o  m
 * @param uri
 *            the location and protocol of the document to Download.
 */
public DownloadTask(String uri) {
    this.currentURI = uri;
    httpClient = HttpClients.createDefault();
}

From source file:com.releasequeue.server.ReleaseQueueServer.java

@Override
public HttpResponse uploadPackage(FilePath packagePath, String distribution, String component)
        throws MalformedURLException, IOException {
    String repoType = FilenameUtils.getExtension(packagePath.toString());

    String uploadPath = String.format("%s/%s/repositories/%s/packages?distribution=%s&component=%s",
            this.basePath, this.userName, repoType, distribution, component);
    URL uploadPackageUrl = new URL(this.serverUrl, uploadPath);

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost uploadFile = new HttpPost(uploadPackageUrl.toString());
    setAuthHeader(uploadFile);/*from w w  w . j  a  v a 2 s .  c  o  m*/

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addBinaryBody("file", new File(packagePath.toString()), ContentType.APPLICATION_OCTET_STREAM,
            packagePath.getName());
    HttpEntity multipart = builder.build();

    uploadFile.setEntity(multipart);

    HttpResponse response = httpClient.execute(uploadFile);
    return response;
}