List of usage examples for org.apache.http.impl.client HttpClients createDefault
public static CloseableHttpClient createDefault()
From source file:org.wso2.carbon.device.mgt.iot.util.IoTUtil.java
/** * Return a http client instance//from w ww . j a v a2 s . c o m * @param protocol- service endpoint protocol http/https * @return */ public static HttpClient getHttpClient(int port, String protocol) throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { HttpClient httpclient; if (HTTPS_PROTOCOL.equals(protocol)) { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); } else { httpclient = HttpClients.createDefault(); } return httpclient; }
From source file:org.llorllale.youtrack.api.session.UsernamePasswordIT.java
/** * Returns Session when logging in./*w ww. j av a2 s . c om*/ * @throws Exception unexpected */ @Test public void login() throws Exception { final IntegrationTestsConfig config = new IntegrationTestsConfig(); assertThat(new UsernamePassword(config.youtrackUrl(), config.youtrackUser(), config.youtrackPwd(), HttpClients.createDefault()).session().cookies(), is(not(empty()))); }
From source file:org.openo.nfvo.jujuvnfmadapter.common.DownloadCsarManager.java
/** * Download from given URL to given file location. * @param url String//w w w . j a v a2 s.co m * @param filepath String * @return */ public static String download(String url, String filepath) { String status = ""; try { CloseableHttpClient client = HttpClients.createDefault(); HttpGet httpget = new HttpGet(url); CloseableHttpResponse response = client.execute(httpget); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); if (filepath == null) { filepath = getFilePath(response); //NOSONAR } File file = new File(filepath); file.getParentFile().mkdirs(); FileOutputStream fileout = new FileOutputStream(file); byte[] buffer = new byte[CACHE]; int ch; while ((ch = is.read(buffer)) != -1) { fileout.write(buffer, 0, ch); } is.close(); fileout.flush(); fileout.close(); status = Constant.DOWNLOADCSAR_SUCCESS; } catch (Exception e) { status = Constant.DOWNLOADCSAR_FAIL; LOG.error("Download csar file failed! " + e.getMessage(), e); } return status; }
From source file:org.imsglobal.caliper.request.ApacheHttpRequestor.java
/** * Init method//from www . jav a 2 s . c om */ public static synchronized void initialize() { if (httpClient == null) { httpClient = HttpClients.createDefault(); } }
From source file:com.beginner.core.utils.HttpUtil.java
/** * <p>To request the POST way.</p> * /*from w ww .j av a 2 s . c o m*/ * @param url request URI * @param json request parameter(json format string) * @param timeout request timeout time in milliseconds(The default timeout time for 30 seconds.) * @return String response result * @throws Exception * @since 1.0.0 */ public static String post(String url, String json, Integer timeout) throws Exception { // Validates input if (StringUtils.isBlank(url)) throw new IllegalArgumentException("The url cannot be null and cannot be empty."); //The default timeout time for 30 seconds if (null == timeout) timeout = 30000; String result = null; CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; try { httpClient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout) .setConnectTimeout(timeout).build(); HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig); httpPost.setHeader("Content-Type", "text/plain"); httpPost.setEntity(new StringEntity(json, "UTF-8")); httpResponse = httpClient.execute(httpPost); HttpEntity entity = httpResponse.getEntity(); result = EntityUtils.toString(entity); EntityUtils.consume(entity); } catch (Exception e) { logger.error("POST?", e); return null; } finally { if (null != httpResponse) httpResponse.close(); if (null != httpClient) httpClient.close(); } return result; }
From source file:org.jasig.cas.web.LicenceFilter.java
public void init(FilterConfig config) throws ServletException { //licence/*w w w.j a v a 2 s .c o m*/ String liurl = config.getInitParameter("liurl"); if (liurl == null || liurl.isEmpty()) { throw new ServletException(); } CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(liurl); httpGet.addHeader("accept", "application/json"); CloseableHttpResponse response1 = null; try { response1 = httpclient.execute(httpGet); if (response1.getStatusLine().getStatusCode() != 200) { System.out.println("licence "); throw new ServletException(); } HttpEntity entity1 = response1.getEntity(); BufferedReader br = new BufferedReader(new InputStreamReader((entity1.getContent()))); String output; StringBuilder sb = new StringBuilder(); while ((output = br.readLine()) != null) { sb.append(output); } JSONObject jsonObject = new JSONObject(sb.toString()); String error = jsonObject.getString("code"); if (!error.equals("S_OK")) { System.out.println("licence "); throw new ServletException(); } String strexprietime = jsonObject.getJSONObject("var").getJSONObject("licInfo").getString("expireTime"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); this.expiretime = df.parse(strexprietime).getTime(); EntityUtils.consume(entity1); } catch (Exception e) { e.printStackTrace(); } finally { try { response1.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:de.l3s.boilerpipe.sax.HTMLFetcher.java
public static HTMLDocument fetch(final String url) throws IOException { //DefaultHttpClient httpclient = new DefaultHttpClient(); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet request = new HttpGet(url.toString()); request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.104 Safari/537.36"); request.setHeader("Referer", "http://www.google.com"); HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity(); //System.out.println("Response Code: " + //response.getStatusLine().getStatusCode()); ContentType contentType = ContentType.getOrDefault(entity); Charset charset = contentType.getCharset(); if (charset == null) { charset = Charset.forName("gb2312"); }/*from w ww . j a v a2 s. co m*/ BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent(), charset)); StringBuilder builder = new StringBuilder(); String aux = ""; Charset cs = Charset.forName("utf8"); boolean charsetFlag = false; while ((aux = rd.readLine()) != null) { if (aux != null && !charsetFlag && (aux.contains("http-equiv") || !aux.contains("src"))) { Matcher m = PAT_CHARSET_REX.matcher(aux); if (m.find()) { final String cName = m.group(1); charsetFlag = true; try { cs = Charset.forName(cName); break; } catch (UnsupportedCharsetException e) { // keep default } } } //builder.append(aux); //System.out.println(builder.toString()); } HttpGet request2 = new HttpGet(url.toString()); request2.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.104 Safari/537.36"); request2.setHeader("Referer", "http://www.google.com"); HttpResponse response2 = httpclient.execute(request2); HttpEntity entity2 = response2.getEntity(); contentType = ContentType.getOrDefault(entity2); charset = contentType.getCharset(); if (charset == null) charset = cs; //if(charset.name().toLowerCase().equals("gb2312")) // charset = Charset.forName("gbk"); BufferedReader rd2 = new BufferedReader(new InputStreamReader(entity2.getContent(), charset)); while ((aux = rd2.readLine()) != null) { builder.append(aux); //System.out.println(builder.toString()); } String text = builder.toString(); //System.out.println(text); rd.close(); rd2.close(); return new HTMLDocument(text, cs); //sometimes cs not equal to charset }
From source file:org.hawkular.alerter.prometheus.PrometheusQueryTest.java
@Ignore // Requires manually running Prom on localhost:9090 @Test/*from ww w. j av a 2 s . c o m*/ public void queryTest() throws Exception { CloseableHttpClient client = HttpClients.createDefault(); StringBuffer url = new StringBuffer("http://localhost:9090"); url.append("/api/v1/query?query="); url.append("up"); HttpGet getRequest = new HttpGet(url.toString()); HttpResponse response = client.execute(getRequest); if (response.getStatusLine().getStatusCode() != 200) { String msg = String.format("Prometheus GET failed. Status=[%d], message=[%s], url=[%s]", response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), url.toString()); System.out.println(msg); fail(); } else { try { QueryResponse queryResponse = JsonUtil.getMapper().readValue(response.getEntity().getContent(), QueryResponse.class); assertEquals("success", queryResponse.getStatus()); QueryResponse.Data data = queryResponse.getData(); assertEquals("vector", data.getResultType()); QueryResponse.Result[] result = data.getResult(); assertEquals(1, result.length); QueryResponse.Result r = result[0]; assertEquals("up", r.getMetric().get("__name__")); assertEquals("prometheus", r.getMetric().get("job")); assertEquals(2, r.getValue().length); long tsMillis = Double.valueOf((double) r.getValue()[0] * 1000).longValue(); assertEquals(String.valueOf(r.getValue()[0]), String.valueOf(System.currentTimeMillis()).length(), String.valueOf(tsMillis).length()); assertEquals("1", r.getValue()[1]); } catch (IOException e) { String msg = String.format("Failed to Map prom response [%s]: %s", response.getEntity(), e); System.out.println(msg); fail(); } } client.close(); }
From source file:no.kantega.commons.taglib.util.GetHtmlTag.java
public int doStartTag() throws JspException { HttpGet get = new HttpGet(url); HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); get.setHeader("User-Agent", request.getHeader("User-Agent")); CloseableHttpClient httpclient = HttpClients.createDefault(); try (CloseableHttpResponse response = httpclient.execute(get)) { HttpEntity entity = response.getEntity(); if (entity != null) { pageContext.getOut().write(IOUtils.toString(entity.getContent())); }/*from w ww. ja v a 2s .com*/ } catch (IOException e) { log.error("Error getting html", e); } return SKIP_BODY; }
From source file:email.mandrill.SendMail.java
public static void checkPingPong() { try {// w w w . j a v a2s . c o m HttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost("https://mandrillapp.com/api/1.0/users/ping.json"); JSONObject obj = new JSONObject(); obj.put("key", SendEmail.MANDRILL_KEY); String request = obj.toString(); HttpEntity entity = new ByteArrayEntity(request.getBytes("UTF-8")); httppost.setEntity(entity); //Execute and get the response. HttpResponse response = httpclient.execute(httppost); HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { InputStream instream = responseEntity.getContent(); try { StringWriter writer = new StringWriter(); IOUtils.copy(instream, writer, "UTF-8"); String theString = writer.toString(); logger.log(Level.INFO, theString); } finally { instream.close(); } } } catch (Exception e) { logger.log(Level.SEVERE, util.Utility.logMessage(e, "Exception while updating org name:", null)); } }