List of usage examples for org.apache.http.impl.client DefaultHttpClient getConnectionManager
public synchronized final ClientConnectionManager getConnectionManager()
From source file:org.openiot.gsn.utils.VSMonitor.java
public static void readStatus(GSNSessionAddress gsnSessionAddress) throws Exception { String httpAddress = gsnSessionAddress.getURL(); DefaultHttpClient client = new DefaultHttpClient(); if (gsnSessionAddress.needsPassword()) { client.getCredentialsProvider().setCredentials( new AuthScope(gsnSessionAddress.getHost(), gsnSessionAddress.getPort()/*, GSN_REALM*/), new UsernamePasswordCredentials(gsnSessionAddress.getUsername(), gsnSessionAddress.getPassword())); }//from w w w . ja v a 2 s .co m logger.warn("Querying server: " + httpAddress); HttpGet get = new HttpGet(httpAddress); try { // execute the GET, getting string directly ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(get, responseHandler); parseXML(responseBody); } catch (HttpResponseException e) { errorsBuffer.append("HTTP 401 Authentication Needed for : ").append(httpAddress).append("\n"); } catch (UnknownHostException e) { errorsBuffer.append("Unknown host: ").append(httpAddress).append("\n"); nHostsDown++; } catch (ConnectException e) { errorsBuffer.append("Connection refused to host: ").append(httpAddress).append("\n"); nHostsDown++; } finally { // release any connection resources used by the method client.getConnectionManager().shutdown(); } }
From source file:org.opencastproject.kernel.http.impl.HttpClientImpl.java
/** * Creates a new client that can deal with all kinds of oddities with regards to http/https connections. * /*from w ww . j av a 2 s . co m*/ * @return the client */ private DefaultHttpClient makeHttpClient() { DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); try { logger.debug("Installing forgiving hostname verifier and trust managers"); X509TrustManager trustManager = createTrustManager(); X509HostnameVerifier hostNameVerifier = createHostNameVerifier(); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { trustManager }, new SecureRandom()); SSLSocketFactory ssf = new SSLSocketFactory(sslContext, hostNameVerifier); ClientConnectionManager ccm = defaultHttpClient.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", 443, ssf)); } catch (NoSuchAlgorithmException e) { logger.error("Error creating context to handle TLS connections: {}", e.getMessage()); } catch (KeyManagementException e) { logger.error("Error creating context to handle TLS connections: {}", e.getMessage()); } return defaultHttpClient; }
From source file:com.fatminds.cmis.AlfrescoCmisHelper.java
/** * This is here and needed because Alfresco CMIS and Chemistry don't play nice together for relationship deletes * as of Alfresco 3.4.2-5 & Chemistry 0.3.0. The problem is that for whatever reason Chemistry strips the "assoc:" prefix * off of the relationship ID that ends up on the end of the Delete URL, like this - /alfresco/service/cmis/rel/assoc:363. * Left to its own devices, Relationship.delete() will end up issuing a URL like /alfresco/service/cmis/rel/363, and Alfresco * will barf. This will hopefully be fixed in Alfesco 4.x. * @param proto/*from www . j a v a 2 s . c o m*/ * @param host * @param port * @param user * @param pass * @param assocId * @return */ public static boolean deleteRelationship(String proto, String host, int port, String user, String pass, String assocId) { DefaultHttpClient client = new DefaultHttpClient(); try { client.getCredentialsProvider().setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(user, pass)); HttpDelete delete = new HttpDelete( proto + "://" + host + ":" + port + "/alfresco/service/cmis/rel/" + assocId); log.info("Sending " + delete.toString()); HttpResponse resp = client.execute(delete); if (resp.getStatusLine().getStatusCode() > 299) { // Alf returns "204 No Content" for success... :-( throw new RuntimeException("Get failed (" + resp.getStatusLine().getStatusCode() + ") because " + resp.getStatusLine().getReasonPhrase()); } } catch (ClientProtocolException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { client.getConnectionManager().shutdown(); } return true; }
From source file:es.logongas.iothome.agent.http.Http.java
public Object post(URL url, Object data) { try {// w ww. jav a 2 s . c o m DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(url.toURI()); StringEntity input = new StringEntity(objectMapper.writeValueAsString(data)); input.setContentType("application/json"); postRequest.setEntity(input); HttpResponse response = httpClient.execute(postRequest); String output = inputStreamToString(response.getEntity().getContent()); if (response.getStatusLine().getStatusCode() != 201) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + "\n" + output); } httpClient.getConnectionManager().shutdown(); return objectMapper.readValue(output, data.getClass()); } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:com.ibm.sbt.services.util.SSLUtil.java
public static DefaultHttpClient wrapHttpClient(DefaultHttpClient base) { try {//from w w w. j a va2 s. c om // Create and assign a dummy TrustManager SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] cert, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] cert, String s) throws CertificateException { } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx); // When Apache Client AllowAllHostnameVerifier is strict, this should be used // Stays here for reference X509HostnameVerifier verifier = new X509HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } @Override public void verify(String s, SSLSocket sslSession) throws IOException { } @Override public void verify(String s, String[] ss1, String[] ss2) throws SSLException { } @Override public void verify(String s, X509Certificate cerst) throws SSLException { } }; ssf.setHostnameVerifier(verifier); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", ssf, 443)); return new DefaultHttpClient(ccm, base.getParams()); } catch (Exception ex) { ex.printStackTrace(); return null; } }
From source file:com.ibm.xsp.xflow.activiti.util.HttpClientUtil.java
public static String post(String url, Cookie[] cookies, String content) { String body = null;/*from w w w.j av a2s.com*/ try { StringBuffer buffer = new StringBuffer(); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(url); StringEntity input = new StringEntity(content); input.setContentType("application/json"); postRequest.setEntity(input); httpClient.setCookieStore(new BasicCookieStore()); String hostName = new URL(url).getHost(); String domain = hostName.substring(hostName.indexOf(".")); for (int i = 0; i < cookies.length; i++) { if (logger.isLoggable(Level.FINEST)) { logger.finest("Cookie:" + cookies[i].getName() + ":" + cookies[i].getValue() + ":" + cookies[i].getDomain() + ":" + cookies[i].getPath()); } BasicClientCookie cookie = new BasicClientCookie(cookies[i].getName(), cookies[i].getValue()); cookie.setVersion(0); cookie.setDomain(domain); cookie.setPath("/"); httpClient.getCookieStore().addCookie(cookie); } HttpResponse response = httpClient.execute(postRequest); BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; if (logger.isLoggable(Level.FINEST)) { logger.finest("Output from Server .... \n"); } while ((output = br.readLine()) != null) { if (logger.isLoggable(Level.FINEST)) { logger.finest(output); } buffer.append(output); } httpClient.getConnectionManager().shutdown(); body = buffer.toString(); } catch (Exception e) { e.printStackTrace(); } return body; }
From source file:se.vgregion.incidentreport.pivotaltracker.impl.PivotalTrackerServiceImpl.java
@Override public void addAttachmentToStory(String projectId, PTStory story) { logger.info("Adding attachments..."); String token = getUserToken(ptUser, ptPwd); for (Attachment attachment : story.getAttachments()) { DefaultHttpClient client = getNewClient(); try {/*from w w w. j a v a 2 s . co m*/ String uploadUrl = getUploadUrl(story); HttpResponse response = HTTPUtils.makePostAttachments(uploadUrl, token, client, attachment); logUploadResponse(story, attachment, response); } catch (Exception e) { throw new RuntimeException("Failed to add attachment to PivotalTracker", e); } finally { client.getConnectionManager().shutdown(); } } }
From source file:com.norconex.collector.http.client.impl.DefaultHttpClientInitializer.java
@Override public void initializeHTTPClient(DefaultHttpClient httpClient) { // Time out after 30 seconds. //TODO Make configurable. httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT); // Add support for FTP websites (FTP served by HTTP server). Scheme ftp = new Scheme("ftp", FTP_PORT, new PlainSocketFactory()); httpClient.getConnectionManager().getSchemeRegistry().register(ftp); //TODO make charset configurable instead since UTF-8 is not right // charset for URL specifications. It is used here to overcome // so invalid redirect errors, where the redirect target URL is not // URL-Encoded and has non-ascii values, and fails // (e.g. like ja.wikipedia.org). // Can consider a custom RedirectStrategy too if need be. httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, "UTF-8"); if (StringUtils.isNotBlank(proxyHost)) { httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort)); if (StringUtils.isNotBlank(proxyUsername)) { httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUsername, proxyPassword)); }//from www. j av a 2s. c om } if (!cookiesDisabled) { httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); } if (AUTH_METHOD_FORM.equalsIgnoreCase(authMethod)) { authenticateUsingForm(httpClient); } else if (AUTH_METHOD_BASIC.equalsIgnoreCase(authMethod)) { setupBasicDigestAuth(httpClient); } else if (AUTH_METHOD_DIGEST.equalsIgnoreCase(authMethod)) { setupBasicDigestAuth(httpClient); } if (userAgent != null) { httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, userAgent); } }
From source file:com.meschbach.psi.util.EchoApplication.java
public Properties echoInitParameters() throws IOException { /*/*from w ww.jav a 2 s .co m*/ * Initialize our HTTP client */ DefaultHttpClient hc = new DefaultHttpClient(); try { /* * Build our request */ String url = contextURL + "/DumpInitPropsServlet"; HttpGet get = new HttpGet(url); /* * Issue the request */ HttpResponse response = hc.execute(get); if (response.getStatusLine().getStatusCode() != 200) { throw new IOException("Unexpected result code: " + response.getStatusLine().getStatusCode()); } Properties result = new Properties(); result.load(response.getEntity().getContent()); return result; } finally { hc.getConnectionManager().shutdown(); } }
From source file:org.openiot.gsn.utils.GSNMonitor.java
public static void readStatus(GSNSessionAddress gsnSessionAddress) throws Exception { String httpAddress = gsnSessionAddress.getURL(); DefaultHttpClient client = new DefaultHttpClient(); if (gsnSessionAddress.needsPassword()) { client.getCredentialsProvider().setCredentials( new AuthScope(gsnSessionAddress.getHost(), gsnSessionAddress.getPort()/*, GSN_REALM*/), new UsernamePasswordCredentials(gsnSessionAddress.getUsername(), gsnSessionAddress.getPassword())); }/*from w w w . j av a 2 s. c o m*/ logger.warn("Querying server: " + httpAddress); HttpGet get = new HttpGet(httpAddress); try { // execute the GET, getting string directly ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(get, responseHandler); parseXML(responseBody); } catch (HttpResponseException e) { errorsBuffer.append("HTTP 401 Authentication Needed for : ").append(httpAddress).append("\n"); } catch (UnknownHostException e) { errorsBuffer.append("Unknown host: ").append(httpAddress).append("\n"); nHostsDown++; } catch (ConnectException e) { errorsBuffer.append("Connection refused to host: ").append(httpAddress).append("\n"); raiseStatusTo(STATUS_CRITICAL); nHostsDown++; } finally { // release any connection resources used by the method client.getConnectionManager().shutdown(); } }