List of usage examples for org.apache.http.impl.client DefaultHttpClient getConnectionManager
public synchronized final ClientConnectionManager getConnectionManager()
From source file:org.wso2.carbon.databridge.agent.internal.endpoint.thrift.client.ThriftSecureClientPoolFactory.java
@Override public Object createClient(String protocol, String hostName, int port) throws DataEndpointAgentSecurityException { String trustStore, trustStorePw; if (protocol.equalsIgnoreCase(DataEndpointConfiguration.Protocol.TCP.toString())) { if (params == null) { if (getTrustStore() == null) { trustStore = System.getProperty("javax.net.ssl.trustStore"); if (trustStore == null) { throw new DataEndpointAgentSecurityException("No trustStore found"); } else { setTrustStore(trustStore); }/*from www . j a v a2 s . c o m*/ } if (getTrustStorePassword() == null) { trustStorePw = System.getProperty("javax.net.ssl.trustStorePassword"); if (trustStorePw == null) { throw new DataEndpointAgentSecurityException("No trustStore password found"); } else { setTrustStorePassword(trustStorePw); } } params = new TSSLTransportFactory.TSSLTransportParameters(); params.setTrustStore(getTrustStore(), getTrustStorePassword()); } TTransport receiverTransport = null; try { receiverTransport = TSSLTransportFactory.getClientSocket(hostName, port, 0, params); TProtocol tProtocol = new TBinaryProtocol(receiverTransport); return new ThriftSecureEventTransmissionService.Client(tProtocol); } catch (TTransportException e) { throw new DataEndpointAgentSecurityException( "Error while trying to connect to " + protocol + "://" + hostName + ":" + port, e); } } else { //TODO:Error thrown when connecting in http in tests... try { TrustManager easyTrustManager = new X509TrustManager() { public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { } public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { easyTrustManager }, null); SSLSocketFactory sf = new SSLSocketFactory(sslContext); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme httpsScheme = new Scheme("https", sf, port); DefaultHttpClient client = new DefaultHttpClient(); client.getConnectionManager().getSchemeRegistry().register(httpsScheme); THttpClient tclient = new THttpClient("https://" + hostName + ":" + port + "/securedThriftReceiver", client); TProtocol tProtocol = new TCompactProtocol(tclient); ThriftSecureEventTransmissionService.Client authClient = new ThriftSecureEventTransmissionService.Client( tProtocol); tclient.open(); return authClient; } catch (Exception e) { throw new DataEndpointAgentSecurityException("Cannot create Secure client for " + "https://" + hostName + ":" + port + "/securedThriftReceiver", e); } } }
From source file:core.HttpClient.java
/** * gets the checksum of the updated file * /* w ww.jav a2 s . c o m*/ * @return String- the checksum */ public static String getUpdateFileChecksum() { DefaultHttpClient httpclient = new DefaultHttpClient(); try { HttpResponse response; HttpEntity entity; HttpPost httpost = new HttpPost(COMPANY_WEBSITE); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("checksum", "")); httpost.setEntity(new UrlEncodedFormEntity(nvps)); response = httpclient.execute(httpost); entity = response.getEntity(); String data = "", line; BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent())); while ((line = br.readLine()) != null) { data += line; } if (data.equals("")) { return null; } else { return data; } } catch (ClientProtocolException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:org.globus.crux.security.ClientTest.java
/** * Test a client using valid credentials * /*from www . j a v a2s . c o m*/ * @throws Exception * if this happens, the test fails. */ @Test public void testValid() throws Exception { SSLConfigurator config = getConfig("classpath:/mykeystore.properties"); SSLSocketFactory fac = new SSLSocketFactory(config.getSSLContext()); fac.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); DefaultHttpClient httpclient = new DefaultHttpClient(); Scheme scheme = new Scheme("https", fac, getPort()); httpclient.getConnectionManager().getSchemeRegistry().register(scheme); HttpGet httpget = new HttpGet("https://localhost/"); System.out.println("executing request" + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } if (entity != null) { entity.consumeContent(); } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system stores httpclient.getConnectionManager().shutdown(); }
From source file:com.wbtech.ums.NetworkUtil.java
public static MyMessage Post(String url, String data) { CobubLog.d(UmsConstants.LOG_TAG, NetworkUtil.class, "URL = " + url); CobubLog.d(UmsConstants.LOG_TAG, NetworkUtil.class, "LENGTH:" + data.length() + " *Data = " + data + "*"); if (!hasInitSSL && UmsConstants.SDK_SECURITY_LEVEL.equals("2")) { initSSL();/* www .j a va2s. co m*/ hasInitSSL = true; } BasicHttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT); HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT); DefaultHttpClient httpclient = null; /*SDK??: * 1,CPOS:???sslSDK_SSL=true;??dn(?dnSDK_HTTPS_DNnone) * 2,HTTPS???????https? * 3,http */ if (UmsConstants.SDK_SECURITY_LEVEL.equals("2")) { httpclient = new DefaultHttpClient(httpParams); // cpos with dn check if (!UmsConstants.SDK_HTTPS_DN.equals("none")) { SSLSocketFactory mysf = null; try { mysf = new CposSSLSocketFactory(); if (serverUrl == null) { serverUrl = new URL(url); serverPort = ((serverUrl.getPort() == -1) ? serverUrl.getDefaultPort() : serverUrl.getPort()); } httpclient.getConnectionManager().getSchemeRegistry() .register(new Scheme(serverUrl.getProtocol(), mysf, serverPort)); } catch (Exception e) { CobubLog.d(UmsConstants.LOG_TAG, NetworkUtil.class, e.toString()); } } } else if (UmsConstants.SDK_SECURITY_LEVEL.equals("1") && url.toLowerCase().startsWith("https")) { // for https with company cert if (serverPort < 0) { serverPort = getPort(); } CobubLog.d(UmsConstants.LOG_TAG, NetworkUtil.class, "InitSSL port is:" + serverPort); SchemeRegistry schReg = new SchemeRegistry(); schReg.register(new Scheme("https", SSLCustomSocketFactory.getSocketFactory(), serverPort)); ClientConnectionManager connMgr = new ThreadSafeClientConnManager(httpParams, schReg); httpclient = new DefaultHttpClient(connMgr, httpParams); } else { httpclient = new DefaultHttpClient(httpParams); } processCookieRejected(httpclient); MyMessage message = new MyMessage(); try { HttpPost httppost = new HttpPost(url); StringEntity se = new StringEntity("content=" + URLEncoder.encode(data), HTTP.UTF_8); se.setContentType("application/x-www-form-urlencoded"); httppost.setEntity(se); HttpResponse response = httpclient.execute(httppost); CobubLog.d(UmsConstants.LOG_TAG, NetworkUtil.class, "Status code=" + response.getStatusLine().getStatusCode()); String returnXML = EntityUtils.toString(response.getEntity()); int status = response.getStatusLine().getStatusCode(); String returnContent = URLDecoder.decode(returnXML, "UTF-8"); CobubLog.d(UmsConstants.LOG_TAG, NetworkUtil.class, "returnString = " + returnContent); //TODO:???200okjson??????????flag<0 //?flag??? switch (status) { case 200: message.setSuccess(isJson(returnContent)); message.setMsg(returnContent); break; default: Log.e("error", status + returnContent); message.setSuccess(false); message.setMsg(returnContent); break; } } catch (Exception e) { message.setSuccess(false); message.setMsg(e.toString()); } return message; }
From source file:org.wso2.carbon.databridge.agent.thrift.internal.pool.client.secure.SecureClientPoolFactory.java
@Override public ThriftSecureEventTransmissionService.Client makeObject(Object key) throws AgentSecurityException, TTransportException { String[] keyElements = key.toString().split(AgentConstants.SEPARATOR); if (keyElements[2].equals(ReceiverConfiguration.Protocol.TCP.toString())) { if (params == null) { if (trustStore == null) { trustStore = System.getProperty("javax.net.ssl.trustStore"); if (trustStore == null) { throw new AgentSecurityException("No trustStore found"); }/*from ww w . j a v a 2 s .c om*/ // trustStore = "/home/suho/projects/wso2/trunk/carbon/distribution/product/modules/distribution/target/wso2carbon-4.0.0-SNAPSHOT/repository/resources/security/client-truststore.jks"; } if (trustStorePassword == null) { trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword"); if (trustStorePassword == null) { throw new AgentSecurityException("No trustStore password found"); } //trustStorePassword = "wso2carbon"; } params = new TSSLTransportFactory.TSSLTransportParameters(); params.setTrustStore(trustStore, trustStorePassword); } String[] hostNameAndPort = keyElements[3].split(AgentConstants.HOSTNAME_AND_PORT_SEPARATOR); TTransport receiverTransport = null; try { receiverTransport = TSSLTransportFactory.getClientSocket( HostAddressFinder.findAddress(hostNameAndPort[0]), Integer.parseInt(hostNameAndPort[1]), 0, params); } catch (SocketException ignored) { //already checked } TProtocol protocol = new TBinaryProtocol(receiverTransport); return new ThriftSecureEventTransmissionService.Client(protocol); } else { try { TrustManager easyTrustManager = new X509TrustManager() { public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { } public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; String[] hostNameAndPort = keyElements[3].split(AgentConstants.HOSTNAME_AND_PORT_SEPARATOR); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { easyTrustManager }, null); SSLSocketFactory sf = new SSLSocketFactory(sslContext); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme httpsScheme = new Scheme("https", sf, Integer.parseInt(hostNameAndPort[1])); DefaultHttpClient client = new DefaultHttpClient(); client.getConnectionManager().getSchemeRegistry().register(httpsScheme); THttpClient tclient = new THttpClient("https://" + keyElements[3] + "/securedThriftReceiver", client); TProtocol protocol = new TCompactProtocol(tclient); ThriftSecureEventTransmissionService.Client authClient = new ThriftSecureEventTransmissionService.Client( protocol); tclient.open(); return authClient; } catch (Exception e) { throw new AgentSecurityException("Cannot create Secure client for " + keyElements[3], e); } } }
From source file:core.HttpClient.java
/** * Checks if we have the latest version//from w ww . j a va 2s. co m * * @param version * @return boolean - true if version is not up to date */ public static boolean isUpdateRequired(String version) { DefaultHttpClient httpclient = new DefaultHttpClient(); try { HttpResponse response; HttpEntity entity; HttpPost httpost = new HttpPost(COMPANY_WEBSITE); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("version", version)); httpost.setEntity(new UrlEncodedFormEntity(nvps)); response = httpclient.execute(httpost); entity = response.getEntity(); String data = "", line; BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent())); while ((line = br.readLine()) != null) { data += line; } if (data.startsWith("true")) { return true; } else { return false; } } catch (ClientProtocolException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:net.bither.http.BaseHttpResponse.java
private DefaultHttpClient getThreadSafeHttpClient() { if (getHttpType() == HttpType.BitherApi) { PersistentCookieStore persistentCookieStore = PersistentCookieStore.getInstance(); if (persistentCookieStore.getCookies() == null || persistentCookieStore.getCookies().size() == 0) { CookieFactory.initCookie();//ww w .j a va 2 s .c o m } } DefaultHttpClient httpClient = new DefaultHttpClient(); ClientConnectionManager mgr = httpClient.getConnectionManager(); HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, HttpSetting.HTTP_CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, HttpSetting.HTTP_SO_TIMEOUT); httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params); setCookieStore(httpClient); return httpClient; }
From source file:org.apache.taverna.activities.rest.HTTPRequestHandler.java
/** * TODO - REDIRECTION output:: if there was no redirection, should just show * the actual initial URL?/*from ww w. j ava 2s . co m*/ * * @param httpRequest * @param acceptHeaderValue */ private static HTTPRequestResponse performHTTPRequest(ClientConnectionManager connectionManager, HttpRequestBase httpRequest, RESTActivityConfigurationBean configBean, Map<String, String> urlParameters, CredentialsProvider credentialsProvider) { // headers are set identically for all HTTP methods, therefore can do // centrally - here // If the user wants to set MIME type for the 'Accepts' header String acceptsHeaderValue = configBean.getAcceptsHeaderValue(); if ((acceptsHeaderValue != null) && !acceptsHeaderValue.isEmpty()) { httpRequest.setHeader(ACCEPT_HEADER_NAME, URISignatureHandler.generateCompleteURI(acceptsHeaderValue, urlParameters, configBean.getEscapeParameters())); } // See if user wanted to set any other HTTP headers ArrayList<ArrayList<String>> otherHTTPHeaders = configBean.getOtherHTTPHeaders(); if (!otherHTTPHeaders.isEmpty()) for (ArrayList<String> httpHeaderNameValuePair : otherHTTPHeaders) if (httpHeaderNameValuePair.get(0) != null && !httpHeaderNameValuePair.get(0).isEmpty()) { String headerParameterizedValue = httpHeaderNameValuePair.get(1); String headerValue = URISignatureHandler.generateCompleteURI(headerParameterizedValue, urlParameters, configBean.getEscapeParameters()); httpRequest.setHeader(httpHeaderNameValuePair.get(0), headerValue); } try { HTTPRequestResponse requestResponse = new HTTPRequestResponse(); DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, null); ((DefaultHttpClient) httpClient).setCredentialsProvider(credentialsProvider); HttpContext localContext = new BasicHttpContext(); // Set the proxy settings, if any if (System.getProperty(PROXY_HOST) != null && !System.getProperty(PROXY_HOST).isEmpty()) { // Instruct HttpClient to use the standard // JRE proxy selector to obtain proxy information ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); // Do we need to authenticate the user to the proxy? if (System.getProperty(PROXY_USERNAME) != null && !System.getProperty(PROXY_USERNAME).isEmpty()) // Add the proxy username and password to the list of // credentials httpClient.getCredentialsProvider().setCredentials( new AuthScope(System.getProperty(PROXY_HOST), Integer.parseInt(System.getProperty(PROXY_PORT))), new UsernamePasswordCredentials(System.getProperty(PROXY_USERNAME), System.getProperty(PROXY_PASSWORD))); } // execute the request HttpResponse response = httpClient.execute(httpRequest, localContext); // record response code requestResponse.setStatusCode(response.getStatusLine().getStatusCode()); requestResponse.setReasonPhrase(response.getStatusLine().getReasonPhrase()); // record header values for Content-Type of the response requestResponse.setResponseContentTypes(response.getHeaders(CONTENT_TYPE_HEADER_NAME)); // track where did the final redirect go to (if there was any) HttpHost targetHost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest targetRequest = (HttpUriRequest) localContext .getAttribute(ExecutionContext.HTTP_REQUEST); requestResponse.setRedirectionURL("" + targetHost + targetRequest.getURI()); requestResponse.setRedirectionHTTPMethod(targetRequest.getMethod()); requestResponse.setHeaders(response.getAllHeaders()); /* read and store response body (check there is some content - negative length of content means unknown length; zero definitely means no content...)*/ // TODO - make sure that this test is sufficient to determine if // there is no response entity if (response.getEntity() != null && response.getEntity().getContentLength() != 0) requestResponse.setResponseBody(readResponseBody(response.getEntity())); // release resources (e.g. connection pool, etc) httpClient.getConnectionManager().shutdown(); return requestResponse; } catch (Exception ex) { return new HTTPRequestResponse(ex); } }
From source file:com.github.matthesrieke.simplebroker.AbstractConsumer.java
protected HttpClient createClient() throws Exception { DefaultHttpClient result = new DefaultHttpClient(); SchemeRegistry sr = result.getConnectionManager().getSchemeRegistry(); SSLSocketFactory sslsf = new SSLSocketFactory(new TrustStrategy() { @Override/* w ww . j av a 2 s .com*/ public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }, new AllowTrustedHostNamesVerifier()); Scheme httpsScheme2 = new Scheme("https", 443, sslsf); sr.register(httpsScheme2); return result; }
From source file:edu.harvard.i2b2.eclipse.plugins.metadataLoader.util.FileUtil.java
public static void download(String workingDir, String URL, String filename) throws IOException { workingDir = workingDir + filename;/*from w ww . j ava 2s .co m*/ DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(URL); HttpResponse response = httpclient.execute(httpget); // System.out.println(response.getStatusLine()); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { BufferedInputStream bis = new BufferedInputStream(instream); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(workingDir))); int inByte; while ((inByte = bis.read()) != -1) { bos.write(inByte); } bis.close(); bos.close(); // unzip("ICD10.zip"); } catch (IOException ex) { throw ex; } catch (RuntimeException ex) { httpget.abort(); throw ex; } finally { instream.close(); } httpclient.getConnectionManager().shutdown(); } }