List of usage examples for org.apache.http.impl.client HttpClients createDefault
public static CloseableHttpClient createDefault()
From source file:io.djigger.monitoring.java.instrumentation.subscription.HttpClientTracerTest.java
private CloseableHttpResponse callPost() throws Exception { CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = null; try {//from www .j av a2 s . c o m HttpPost post = new HttpPost("http://localhost:12298"); response = client.execute(post); } catch (IOException e) { e.printStackTrace(); } return response; }
From source file:onl.area51.filesystem.http.client.HttpUtils.java
public static void send(char[] path, Function<char[], String> remoteUri, Function<char[], Path> getPath, Supplier<String> userAgent) throws IOException { if (path == null || path.length == 0) { throw new FileNotFoundException("/"); }//w w w .ja v a2 s. co m String uri = remoteUri.apply(path); if (uri != null) { HttpEntity entity = new PathEntity(getPath.apply(path)); LOG.log(Level.FINE, () -> "Sending " + uri); HttpPut put = new HttpPut(uri); put.setHeader(USER_AGENT, userAgent.get()); put.setEntity(entity); try (CloseableHttpClient client = HttpClients.createDefault()) { try (CloseableHttpResponse response = client.execute(put)) { int returnCode = response.getStatusLine().getStatusCode(); LOG.log(Level.FINE, () -> "ReturnCode " + returnCode + ": " + response.getStatusLine().getReasonPhrase()); } } } }
From source file:com.github.mike10004.jenkinsbbhook.WebhookHandlerTest.java
@Test public void testRelayBuildRequest() throws Exception { System.out.println("testRelayBuildRequest"); MockServerClient jenkinsServer = new MockServerClient("localhost", mockServerRule.getHttpPort()); CrumbData crumbData = new CrumbData("5647382910", ".crumb"); String crumbDataJson = new Gson().toJson(crumbData); String apiToken = "12345"; String username = "betty@example.com"; String projectToken = "09876"; jenkinsServer.when(HttpRequest.request("/crumbIssuer/api/json") // .with ).respond(HttpResponse.response(crumbDataJson).withStatusCode(SC_OK)); String jobName = "my-jenkins-project"; String pushJson = "{}"; jenkinsServer//from w w w.ja v a 2 s.co m .when(HttpRequest.request("/job/" + jobName + "/build").withMethod("POST") .withHeader(crumbData.crumbRequestField, crumbData.crumb) .withQueryStringParameter("token", projectToken)) .respond(HttpResponse.response().withStatusCode(SC_ACCEPTED)); MockServletContext servletContext = new MockServletContext(); MockHttpServletRequest request = new MockHttpServletRequest(servletContext); request.addHeader("X-Event-Key", "repo:push"); servletContext.setInitParameter(ContextAppParams.PARAM_JENKINS_BASE_URL, "http://localhost:" + mockServerRule.getHttpPort()); WebhookHandler instance = new WebhookHandler(new Supplier<CloseableHttpClient>() { @Override public CloseableHttpClient get() { return HttpClients.createDefault(); } }, servletContext); instance.relayBuildRequest(request, jobName, projectToken, username, apiToken, pushJson); }
From source file:org.jboss.as.test.integration.web.multipart.defaultservlet.DefaultServletMultipartConfigTestCase.java
@Test public void testMultipartRequestToDefaultServlet() throws Exception { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost post = new HttpPost(url.toExternalForm() + "/servlet"); post.setEntity(MultipartEntityBuilder.create().addTextBody("file", MESSAGE).build()); HttpResponse response = httpClient.execute(post); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); assertEquals(200, statusLine.getStatusCode()); String result = EntityUtils.toString(entity); Assert.assertEquals(MESSAGE, result); }// w w w . j a va 2 s .com }
From source file:mx.clickfactura.util.TipoCambioUtil.java
public String getTipoCambio(String fecha) throws CustomBadRequestException, CustomNotFoundException, Exception { Pattern pattern = Pattern.compile("^\\d{4}\\-\\d{2}\\-\\d{2}$"); Matcher matcher = null;//from ww w. j a v a 2 s . co m matcher = pattern.matcher(fecha.trim()); if (!matcher.matches()) { throw new CustomBadRequestException("Fecha invalida, el formato debe ser: yyyy-MM-dd"); } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar cal = new GregorianCalendar(); cal.setTime(sdf.parse(fecha)); String dia = (cal.get(Calendar.DATE) < 10) ? "0" + cal.get(Calendar.DATE) : cal.get(Calendar.DATE) + ""; String mes = ((cal.get(Calendar.MONTH) + 1) < 10) ? "0" + (cal.get(Calendar.MONTH) + 1) : (cal.get(Calendar.MONTH) + 1) + ""; String anio = cal.get(Calendar.YEAR) + ""; String fechaInicial = dia + "%2F" + mes + "%2F" + anio; CloseableHttpClient client = HttpClients.createDefault(); CookieStore cookies = new BasicCookieStore(); String[] fechaSeparada = fecha.split("-"); HttpGet get = new HttpGet("http://www.dof.gob.mx/indicadores_detalle.php?cod_tipo_indicador=158&dfecha=" + fechaInicial + "&hfecha=" + fechaInicial); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookies); CloseableHttpResponse response = client.execute(get, httpContext); //System.out.println(response.toString()); //System.out.println(response.getStatusLine()); //System.out.println(response.getEntity().getContentLength()); InputStream in = response.getEntity().getContent(); Header encoding = response.getEntity().getContentEncoding(); String body = IOUtils.toString(in, "UTF-8"); //System.out.println(body); Document doc = Jsoup.parse(body, "UTF-8"); doc = doc.normalise(); //System.out.println(doc.toString()); Elements e = doc.select("table"); Iterator iterator = e.iterator(); pattern = Pattern.compile("^\\d{2}\\.\\d{6}$"); matcher = null; String tipoCambio = null; while (iterator.hasNext()) { Element xd = (Element) iterator.next(); if (xd.getElementsByClass("txt").hasAttr("height")) { if (xd.getElementsByClass("txt").text().split(" ").length == 6) { String cambio = xd.getElementsByClass("txt").text().split(" ")[5]; matcher = pattern.matcher(cambio.trim()); if (matcher.matches()) { tipoCambio = cambio; //System.out.println(tipoCambio); break; } } } } client.close(); response.close(); if (tipoCambio == null || tipoCambio.isEmpty()) { throw new CustomNotFoundException("No hay un tipo de cambio para el da: " + fecha); } return tipoCambio; }
From source file:edu.harvard.hms.dbmi.i2b2.api.I2B2Factory.java
/** * Login into a given i2b2 connection by passing the PM cells information * /*from w ww . j a va 2s . c om*/ * @param connectionURL PM Connection URL * @param domain Domain for the user * @param userName User name * @param password Passowrd * @return Returns the i2b2 token * @throws I2B2InterfaceException An exception occurred */ public String login(String connectionURL, String domain, String userName, String password, boolean saveToken) throws I2B2InterfaceException { String token = null; try { PMCell pmCell = new PMCell(); this.connectionURL = connectionURL; this.domain = domain; this.userName = userName; this.password = password; pmCell.setup(connectionURL, domain, userName, password, false, null); HttpClient httpClient = HttpClients.createDefault(); ConfigureType configureType = pmCell.getUserConfiguration(httpClient, null, new String[] { "undefined" }); if (saveToken) { this.token = configureType.getUser().getPassword().getValue(); this.tokenTimeOut = configureType.getUser().getPassword().getTokenMsTimeout(); } for (ProjectType pt : configureType.getUser().getProject()) { this.projects.put(pt.getId(), pt.getPath()); } this.cellData = configureType.getCellDatas().getCellData(); this.setup = true; } catch (UnsupportedOperationException | JAXBException | I2B2InterfaceException | IOException e) { throw new I2B2InterfaceException("Unable to login", e); } return token; }
From source file:PostTest.PostTest.java
public Map getPostData(String url, Map<String, String> para) throws ClientProtocolException, IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); Map returnMap = new HashMap(); try {//from w w w.j av a 2s . c o m HttpPost httppost = new HttpPost(url); try { if (para != null) { List pl = new ArrayList(); for (Iterator iterator = para.keySet().iterator(); iterator.hasNext();) { String key = (String) iterator.next(); Object ov = para.get(key); if (ov instanceof Integer) { ov = String.valueOf(ov); } pl.add(new BasicNameValuePair(key, ov + "")); } httppost.setEntity(new UrlEncodedFormEntity(pl)); } } catch (Throwable e) { throw new RuntimeException("para=" + para, e); } CloseableHttpResponse response = httpclient.execute(httppost); try { int status = response.getStatusLine().getStatusCode(); returnMap.put("status", status); // ? if (status == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); if (entity != null) { // start ?? InputStream is = entity.getContent(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = in.readLine()) != null) { buffer.append(line); } // end ?? returnMap.put("data", buffer.toString()); } } // else { returnMap.put("StatusCode", response.getStatusLine().getStatusCode()); returnMap.put("ReasonPhrase", response.getStatusLine().getReasonPhrase()); Header[] headers = response.getAllHeaders(); for (Header header : headers) { returnMap.put(header.getName(), header.getValue()); } } // System.out.println( EntityUtils.toString(response.getEntity())); } finally { response.close(); } } finally { httpclient.close(); } return returnMap; }
From source file:org.wuspba.ctams.ws.ITVenueController.java
@Test public void testList() throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); LOG.info("Connecting to " + uri.toString()); HttpGet httpGet = new HttpGet(uri); try (CloseableHttpResponse response = httpclient.execute(httpGet)) { assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING); HttpEntity entity = response.getEntity(); CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity); assertEquals(doc.getVenues().size(), 1); testEquality(doc.getVenues().get(0), TestFixture.INSTANCE.venue); EntityUtils.consume(entity);/*from w w w .ja v a 2 s. c o m*/ } }
From source file:gr.uoc.nlp.opinion.analysis.suggestion.ElasticSearchIntegration.java
/** * * @param commentID// www. j a v a 2 s. c o m * @param sentenceID */ public void removeFromElasticSearch(String commentID, String sentenceID) { CloseableHttpClient httpclient = HttpClients.createDefault(); String deleteURI = this.elasticSearchURI + commentID + "_" + sentenceID; System.out.println(deleteURI); // create DELETE REQUEST HttpDelete httpDelete = new HttpDelete(deleteURI); // send request CloseableHttpResponse response = null; try { response = httpclient.execute(httpDelete); } catch (IOException ex) { Logger.getLogger(ElasticSearchIntegration.class.getName()).log(Level.SEVERE, null, ex); } try { // close response (ideally inside a finally clause in a try/catch) response.close(); } catch (IOException ex) { Logger.getLogger(ElasticSearchIntegration.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.elasticsearch.plugin.ResponseHeaderPluginTests.java
private HttpRequestBuilder httpClient() { return new HttpRequestBuilder(HttpClients.createDefault()) .httpTransport(internalCluster().getDataNodeInstance(HttpServerTransport.class)); }