List of usage examples for org.apache.http.impl.client DefaultHttpClient getConnectionManager
public synchronized final ClientConnectionManager getConnectionManager()
From source file:org.jenkinsci.plugins.appio.service.AppioService.java
/** * @param appId//ww w.j a v a 2s . c o m * @param urlUpload * @return * @throws Exception */ public AppioVersionObject addVersion(String appId, String urlUpload) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); ResponseHandler<String> handler = new BasicResponseHandler(); AppioVersion newVersion = new AppioVersion(); AppioVersionObject versionObj = new AppioVersionObject(); try { // Construct {"version": ... } message body versionObj.setApp_id(appId); versionObj.setBundle_url(urlUpload); newVersion.setVersion(versionObj); LOGGER.fine("AppioService.addVersion() Request: " + new Gson().toJson(newVersion)); // Send new version REST call to Appio httpPostVersions.addHeader("Authorization", "Basic " + apiKey); httpPostVersions.addHeader("Content-Type", "application/json"); httpPostVersions.addHeader("Accept", appio_v1); StringEntity reqBody = new StringEntity(new Gson().toJson(newVersion), ContentType.create("application/json", "UTF-8")); httpPostVersions.setEntity(reqBody); HttpResponse response = httpClient.execute(httpHost, httpPostVersions); String jsonAppioVersion = handler.handleResponse(response); LOGGER.fine("AppioService.addVersion() Response: " + jsonAppioVersion); newVersion = new Gson().fromJson(jsonAppioVersion, AppioVersion.class); } catch (Exception e) { e.getStackTrace(); throw e; } finally { try { httpClient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } return newVersion.getVersion(); }
From source file:com.vmware.bdd.plugin.ironfan.impl.RolePackageMapping.java
@SuppressWarnings("deprecation") private String readDistroManifest() throws Exception { File manifestFile = new File(DISTRO_MANIFEST_FILE_PATH); if (manifestFile.exists()) { // The manifest file is on the local server. // No need to reload the file if it's not modified. if (lastModified != manifestFile.lastModified()) { lastModified = manifestFile.lastModified(); logger.info("last modified date of manifest file changed. Reloading manifest."); } else {/*from w w w . j a v a2 s. c o m*/ return null; } } BufferedReader in = null; DefaultHttpClient httpclient = new DefaultHttpClient(); try { SSLContext sslContext = SSLContexts.custom().useTLS().build(); sslContext.init(null, new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return; } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return; } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }, null); TlsClientConfiguration tlsConfiguration = new TlsClientConfiguration(); SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, tlsConfiguration.getSslProtocols(), tlsConfiguration.getCipherSuites(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme sch = new Scheme("https", 443, socketFactory); httpclient.getConnectionManager().getSchemeRegistry().register(sch); HttpGet httpget = new HttpGet(new URI(distrosManifestUrl)); if (eTag != null) { httpget.addHeader("If-None-Match", eTag); } logger.info("executing request: " + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); if (!manifestFile.exists()) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED) { return null; } else { logger.debug("ETag of manifest file changed. Reloading manifest."); eTag = response.getFirstHeader("ETag").getValue(); ; } } HttpEntity entity = response.getEntity(); in = new BufferedReader(new InputStreamReader(entity.getContent())); StringBuffer sb = new StringBuffer(); String line; while ((line = in.readLine()) != null) { sb.append(line); } EntityUtils.consume(entity); return sb.toString(); } finally { httpclient.getConnectionManager().shutdown(); if (in != null) { in.close(); } } }
From source file:org.jboss.as.test.clustering.cluster.ejb.stateful.StatefulFailoverTestCase.java
/** * Validates failover on server restart of a simple @Stateful bean *///from w ww .ja v a 2 s .com @Test public void failoverOnStop(@ArquillianResource() @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1, @ArquillianResource() @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws Exception { DefaultHttpClient client = org.jboss.as.test.http.util.HttpClientUtils.relaxedCookieHttpClient(); URI uri1 = StatefulServlet.createURI(baseURL1, MODULE_NAME, SimpleIncrementorBean.class.getSimpleName()); URI uri2 = StatefulServlet.createURI(baseURL2, MODULE_NAME, SimpleIncrementorBean.class.getSimpleName()); try { assertEquals(1, queryCount(client, uri1)); assertEquals(2, queryCount(client, uri1)); assertEquals(3, queryCount(client, uri2)); assertEquals(4, queryCount(client, uri2)); stop(CONTAINER_2); assertEquals(5, queryCount(client, uri1)); assertEquals(6, queryCount(client, uri1)); start(CONTAINER_2); assertEquals(7, queryCount(client, uri1)); assertEquals(8, queryCount(client, uri1)); assertEquals(9, queryCount(client, uri2)); assertEquals(10, queryCount(client, uri2)); stop(CONTAINER_1); assertEquals(11, queryCount(client, uri2)); assertEquals(12, queryCount(client, uri2)); start(CONTAINER_1); assertEquals(13, queryCount(client, uri1)); assertEquals(14, queryCount(client, uri1)); assertEquals(15, queryCount(client, uri2)); assertEquals(16, queryCount(client, uri2)); } finally { client.getConnectionManager().shutdown(); } }
From source file:org.miloss.fgsms.bueller.Bueller.java
/** * Sends an HTTP GET request to a url/*from ww w. j a va2 s.c om*/ * * @param endpoint - The URL of the server. (Example: " * http://www.yahoo.com/search") Note: This method will add the question * mark (?wsdl) to the request * @return - OK for 200 messages, all others, the actually response code or * error message */ protected String sendGetRequest(boolean pooled, String endpoint, int depth) { if (depth > 10) { //abort, possible redirect loop return "Aborting due to redirect loop"; } String result = null; String policyUrl = new String(endpoint); if (endpoint.startsWith("http://")) { // Send a GET request to the servlet HttpURLConnection conn = null; try { String originalendpoint = endpoint; if (!endpoint.endsWith("?wsdl")) { endpoint = endpoint + "?wsdl"; } conn = (HttpURLConnection) new URL(endpoint).openConnection(); if (conn.getResponseCode() == 401) { //basic example WWW-Authenticate: Basic realm="fgsms Services" //digest example WWW-Authenticate: Digest realm="fgsms Services", qop="auth", nonce="2569aa2af54f6d47e8472f47f2e3da01", opaque="a39d25cce80574f8255b97052d8f1544" //WWW-Authenticate: Negotiate //WWW-Authenticate: NTLM // String authtype = conn.getHeaderField("WWW-Authenticate"); // if (authtype.toLowerCase().startsWith("digest")) { return sendGetRequestAuth(pooled, endpoint, policyUrl, depth + 1); } else if (conn.getResponseCode() == 404) { //fix for sonatype nexus and non wsdl urls conn = (HttpURLConnection) new URL(originalendpoint).openConnection(); return "Not found"; } else if (conn.getResponseCode() == HttpStatus.SC_MOVED_PERMANENTLY || conn.getResponseCode() == HttpStatus.SC_MOVED_TEMPORARILY || conn.getResponseCode() == HttpStatus.SC_TEMPORARY_REDIRECT) { //follow the redirect String newUrl = conn.getHeaderField("Location"); return sendGetRequest(pooled, newUrl, depth + 1); //System.out.println("Moved to " + newUrl); //should be the new destination url //return "Moved " + conn.getResponseMessage(); } else if (conn.getResponseCode() == HttpStatus.SC_NOT_MODIFIED) { return "OK"; } InputStream inputStream = null; try { inputStream = conn.getInputStream(); byte[] buffer = new byte[1024]; while (inputStream.read(buffer) >= 0) { } inputStream.close(); } catch (Exception f) { } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception ex) { } } } String msg = conn.getResponseMessage(); conn.disconnect(); return msg; } catch (java.net.UnknownHostException ex) { return "Host unknown"; } catch (Exception ex) { return ex.getMessage(); } finally { if (conn != null) { try { conn.disconnect(); } catch (Exception ex) { } } } } else if (endpoint.startsWith("https://")) { if (!endpoint.endsWith("?wsdl")) { endpoint = endpoint + "?wsdl"; } DefaultHttpClient c = new DefaultHttpClient(); try { URL url = new URL(endpoint); int port = url.getPort(); if (port == -1 && endpoint.toLowerCase().startsWith("http:")) { port = 80; } if (port == -1 && endpoint.toLowerCase().startsWith("https:")) { port = 443; } Scheme sch = null; if (sfpki == null) { sch = new Scheme("https", port, sf); } else { sch = new Scheme("https", port, sfpki); } if (endpoint.toLowerCase().startsWith("https:")) { c.getConnectionManager().getSchemeRegistry().register(sch); } HttpGet m = new HttpGet(endpoint); HttpResponse res = c.execute(m); int status = res.getStatusLine().getStatusCode(); try { InputStream content = res.getEntity().getContent(); byte[] buffer = new byte[1024]; while (content.read(buffer) >= 0) { } } catch (Exception f) { } c.getConnectionManager().shutdown(); if (status == 401) { return sendGetRequestAuth(pooled, endpoint, policyUrl, depth + 1); } else if (status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT) { String newUrl = res.getHeaders("Location")[0].getValue(); return sendGetRequest(pooled, newUrl, depth + 1); } else if (status == HttpStatus.SC_NOT_MODIFIED) { return "OK"; } else { return (status < 300) ? "OK" : "offline"; } } catch (Exception ex) { c.getConnectionManager().shutdown(); log.log(Level.WARN, "error caught connecting to " + endpoint, ex); return ex.getMessage(); } } else if (endpoint.startsWith("jms:")) { return doJmsURL(pooled, endpoint); } return "Unknown protocol"; }
From source file:messenger.YahooFinanceAPI.java
public static String httppost(String url, List<NameValuePair> header, String refer, boolean cookie) { DefaultHttpClient httpclient = new DefaultHttpClient(); if (cookie)// ww w .j a v a 2 s . c o m httpclient.setCookieStore(cookiestore); else if (cookiestore1 != null) httpclient.setCookieStore(cookiestore1); if (use_proxy) { HttpHost proxy = new HttpHost(PROXY_NAME, PROXY_PORT); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } HttpPost httpPost = new HttpPost(url); httpPost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); Header[] headers = { new BasicHeader("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"), new BasicHeader("Content-Type", "application/x-www-form-urlencoded"), new BasicHeader("Origin", "http://aomp.judicial.gov.tw"), new BasicHeader("Referer", refer), new BasicHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.55 Safari/534.3") }; httpPost.setHeaders(headers); try { httpPost.setEntity(new UrlEncodedFormEntity(header, "Big5")); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } HttpResponse response = null; String responseString = null; try { response = httpclient.execute(httpPost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { if (cookie) cookiestore = httpclient.getCookieStore(); else cookiestore1 = httpclient.getCookieStore(); responseString = EntityUtils.toString(response.getEntity()); // pG^O 200 OK ~X // System.out.println(responseString); // } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) { Header[] urlh = response.getAllHeaders(); System.out.println(urlh.toString()); } else { System.out.println(response.getStatusLine()); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } httpclient.getConnectionManager().shutdown(); return responseString; }
From source file:org.picketlink.test.trust.tests.JBWSTokenIssuingLoginModuleUnitTestCase.java
private void assertApp(String appUri, String userName, String password, String httpHeader, String httpHeaderValue) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try {/*w w w . j a va 2 s . com*/ httpclient.getCredentialsProvider().setCredentials(new AuthScope(getServerAddress(), 8080), // localhost new UsernamePasswordCredentials(userName, password)); HttpGet httpget = new HttpGet(getTargetURL(appUri)); // http://localhost:8080/test-app-1/test if (httpHeader != null) httpget.addHeader(httpHeader, httpHeaderValue); log.debug("executing request" + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); assertEquals("Http response has to finish with 'HTTP/1.1 200 OK'", 200, response.getStatusLine().getStatusCode()); HttpEntity entity = response.getEntity(); log.debug("Status line: " + response.getStatusLine()); ByteArrayOutputStream baos = new ByteArrayOutputStream((int) entity.getContentLength()); entity.writeTo(baos); String content = baos.toString(); baos.close(); if (log.isTraceEnabled()) { log.trace(content); } Pattern p = Pattern.compile("[.|\\s]*Credential\\[\\d\\]\\=SamlCredential\\[.*\\]", Pattern.DOTALL); Matcher m = p.matcher(content); boolean samlCredPresentOnSubject = m.find(); assertTrue("SamlCredential on subject is missing for (" + appUri + ")", samlCredPresentOnSubject); EntityUtils.consume(entity); } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:org.picketbox.test.jaxrs.RESTEasyStandaloneTestCase.java
/** * This test case tests the encryption of JSON payload * * @throws Exception/*w w w . j a va 2 s . c om*/ */ @Test public void testJAXRS_jsonEncryption() throws Exception { PrivateKey privateKey = getPrivateKey(); String urlStr = "http://localhost:11080/rest/bookstore/"; URL url = new URL(urlStr); DefaultHttpClient httpclient = null; try { httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url.toExternalForm()); httpget.setHeader(JWEInterceptor.CLIENT_ID, "1234"); System.out.println("executing request:" + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); StatusLine statusLine = response.getStatusLine(); System.out.println(statusLine); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } InputStream is = entity.getContent(); String contentString = getContentAsString(is); JSONWebToken jwt = new JSONWebToken(); jwt.setPrivateKey(privateKey); jwt.decode(contentString); JSONObject jsonObject = jwt.getData(); assertNotNull(jsonObject); assertEquals("Harry Potter", jsonObject.getString("name")); System.out.println(jsonObject.toString()); assertEquals(200, statusLine.getStatusCode()); EntityUtils.consume(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:org.apache.juddi.v3.client.mapping.wadl.WADL2UDDI.java
/** * Parses a web accessible WADL file/*w ww . j a v a 2 s . c o m*/ * @param weburl * @param username * @param password * @param ignoreSSLErrors if true, SSL errors are ignored * @return a non-null "Application" object, represeting a WADL's application root XML * Sample code:<br> * <pre> * Application app = WADL2UDDI.parseWadl(new URL("http://server/wsdl.wsdl"), "username", "password", * clerkManager.getClientConfig().isX_To_Wsdl_Ignore_SSL_Errors() ); * </pre> */ public static Application parseWadl(URL weburl, String username, String password, boolean ignoreSSLErrors) { DefaultHttpClient httpclient = null; Application unmarshal = null; try { String url = weburl.toString(); if (!url.toLowerCase().startsWith("http")) { return parseWadl(weburl); } boolean usessl = false; int port = 80; if (url.toLowerCase().startsWith("https://")) { port = 443; usessl = true; } if (weburl.getPort() > 0) { port = weburl.getPort(); } if (ignoreSSLErrors && usessl) { SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", port, new MockSSLSocketFactory())); ClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry); httpclient = new DefaultHttpClient(cm); } else { httpclient = new DefaultHttpClient(); } if (username != null && username.length() > 0 && password != null && password.length() > 0) { httpclient.getCredentialsProvider().setCredentials(new AuthScope(weburl.getHost(), port), new UsernamePasswordCredentials(username, password)); } HttpGet httpGet = new HttpGet(url); try { HttpResponse response1 = httpclient.execute(httpGet); //System.out.println(response1.getStatusLine()); // HttpEntity entity1 = response1.getEntity(); // do something useful with the response body // and ensure it is fully consumed ResponseHandler<String> responseHandler = new BasicResponseHandler(); String handleResponse = responseHandler.handleResponse(response1); StringReader sr = new StringReader(handleResponse); unmarshal = JAXB.unmarshal(sr, Application.class); } finally { httpGet.releaseConnection(); } } catch (Exception e) { log.error(e.getMessage(), e); } finally { if (httpclient != null) { httpclient.getConnectionManager().shutdown(); } } return unmarshal; }
From source file:com.base.httpclient.HttpJsonClient.java
/** * get/*from ww w. jav a2s. com*/ * * @param url * URL * @param params * getkey-value * @return JSON * @throws ClientProtocolException * @throws IOException * @throws URISyntaxException */ public static String get(String url, Map<String, ?> params) throws ClientProtocolException, IOException, URISyntaxException { DefaultHttpClient httpclient = getHttpClient(); try { if (params != null && !(params.isEmpty())) { List<NameValuePair> values = new ArrayList<NameValuePair>(); for (Map.Entry<String, ?> entity : params.entrySet()) { BasicNameValuePair pare = new BasicNameValuePair(entity.getKey(), entity.getValue().toString()); values.add(pare); } String str = URLEncodedUtils.format(values, "UTF-8"); if (url.indexOf("?") > -1) { url += "&" + str; } else { url += "?" + str; } } URL pageURL = new URL(url); //pageUrl?httpget URI uri = new URI(pageURL.getProtocol(), pageURL.getHost(), pageURL.getPath(), pageURL.getQuery(), null); HttpGet httpget = createHttpUriRequest(HttpMethod.GET, uri); httpget.setHeader("Pragma", "no-cache"); httpget.setHeader("Cache-Control", "max-age=0, no-cache, no-store, must-revalidate"); httpget.setHeader("Connection", "keep-alive"); httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); httpget.setHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3"); httpget.setHeader("Accept-Charset", "gbk,utf-8;q=0.7,*;q=0.7"); httpget.setHeader("Referer", url); /*httpget.setHeader("Content-Encoding", "gzip"); httpget.setHeader("Accept-Encoding", "gzip, deflate");*/ //httpget.setHeader("Host", "s.taobao.com"); /*int temp = Integer.parseInt(Math.round(Math.random()*(MingSpiderService.UserAgent.length-1))+"");//??? httpget.setHeader("User-Agent", MingSpiderService.UserAgent[temp]);*/ HttpResponse response = httpclient.execute(httpget); httpclient.getCookieStore().clear(); int resStatu = response.getStatusLine().getStatusCode(); String html = ""; if (resStatu == HttpStatus.SC_OK) {//200 HttpEntity entity = response.getEntity(); if (entity != null) { html = EntityUtils.toString(entity, "GBK"); EntityUtils.consume(entity); } } return html; } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:org.brunocvcunha.taskerbox.core.http.TaskerboxHttpBox.java
/** * Build a new HTTP Client for the given parameters * * @param params/*from ww w.ja v a 2 s . com*/ * @return */ public DefaultHttpClient buildNewHttpClient(HttpParams params) { PoolingClientConnectionManager cxMgr = new PoolingClientConnectionManager( SchemeRegistryFactory.createDefault()); cxMgr.setMaxTotal(100); cxMgr.setDefaultMaxPerRoute(20); DefaultHttpClient httpClient = new DefaultHttpClient(cxMgr, params); httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36"); // httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, // CookiePolicy.BROWSER_COMPATIBILITY); if (this.useNtlm) { httpClient.getAuthSchemes().register("NTLM", new NTLMSchemeFactory()); httpClient.getAuthSchemes().register("BASIC", new BasicSchemeFactory()); httpClient.getAuthSchemes().register("DIGEST", new DigestSchemeFactory()); httpClient.getAuthSchemes().register("SPNEGO", new SPNegoSchemeFactory()); httpClient.getAuthSchemes().register("KERBEROS", new KerberosSchemeFactory()); } try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, getTrustingManager(), new java.security.SecureRandom()); SSLSocketFactory socketFactory = new SSLSocketFactory(sc); Scheme sch = new Scheme("https", 443, socketFactory); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } if (this.useProxy) { if (this.proxySocks) { log.info("Using proxy socks " + this.socksHost + ":" + this.socksPort); System.setProperty("socksProxyHost", this.socksHost); System.setProperty("socksProxyPort", String.valueOf(this.socksPort)); } else { HttpHost proxy = new HttpHost(this.proxyHost, this.proxyPort); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (this.authProxy) { List<String> authPreferences = new ArrayList<>(); if (this.ntlmProxy) { NTCredentials creds = new NTCredentials(this.proxyUser, this.proxyPassword, this.proxyWorkstation, this.proxyDomain); httpClient.getCredentialsProvider() .setCredentials(new AuthScope(this.proxyHost, this.proxyPort), creds); // httpClient.getCredentialsProvider().setCredentials( // AuthScope.ANY, creds); authPreferences.add(AuthPolicy.NTLM); } else { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(this.proxyUser, this.proxyPassword); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); authPreferences.add(AuthPolicy.BASIC); } httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authPreferences); } } } return httpClient; }