List of usage examples for org.apache.http.conn.ssl SSLSocketFactory SSLSocketFactory
public SSLSocketFactory(final SSLContext sslContext)
From source file:com.longle1.facedetection.TimedAsyncHttpResponseHandler.java
public void executePut(String putURL, RequestParams params, byte[] bb) { try {//from w ww. j a va2s. c om AsyncHttpClient client = new AsyncHttpClient(); ByteArrayEntity bae = null; bae = new ByteArrayEntity(bb); bae.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/octet-stream")); // Add SSL KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(mContext.getResources().openRawResource(R.raw.truststore), "changeit".toCharArray()); SSLSocketFactory sf = new SSLSocketFactory(trustStore); client.setSSLSocketFactory(sf); client.setTimeout(30000); client.put(null, putURL + "?" + params.toString(), bae, null, this); } catch (Exception e) { e.printStackTrace(); } Log.i("executePut", "done"); }
From source file:android.net.http.HttpsThroughHttpProxyTest.java
public void testConnectViaHttpProxyToHttps() throws IOException, InterruptedException { TestSSLContext testSSLContext = TestSSLContext.create(); MockWebServer proxy = new MockWebServer(); proxy.useHttps(testSSLContext.serverContext.getSocketFactory(), true); MockResponse connectResponse = new MockResponse().setResponseCode(200); connectResponse.getHeaders().clear(); proxy.enqueue(connectResponse);//from w w w . ja va 2 s . c o m proxy.enqueue(new MockResponse().setResponseCode(200).setBody("this response comes via a secure proxy")); proxy.play(); HttpClient httpProxyClient = new DefaultHttpClient(); HttpHost proxyHost = new HttpHost("localhost", proxy.getPort()); httpProxyClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost); SSLSocketFactory sslSocketFactory = new SSLSocketFactory(testSSLContext.clientContext.getSocketFactory()); sslSocketFactory.setHostnameVerifier(new AllowAllHostnameVerifier()); httpProxyClient.getConnectionManager().getSchemeRegistry() .register(new Scheme("https", sslSocketFactory, 443)); HttpResponse response = httpProxyClient.execute(new HttpGet("https://android.com/foo")); assertEquals("this response comes via a secure proxy", contentToString(response)); RecordedRequest connect = proxy.takeRequest(); assertEquals("Connect line failure on proxy " + proxyHost.toHostString(), "CONNECT android.com:443 HTTP/1.1", connect.getRequestLine()); assertContains(connect.getHeaders(), "Host: android.com"); RecordedRequest get = proxy.takeRequest(); assertEquals("GET /foo HTTP/1.1", get.getRequestLine()); assertContains(get.getHeaders(), "Host: android.com"); }
From source file:org.ckan.Connection.java
/** * Makes a POST request// w w w . j av a 2 s . c om * * Submits a POST HTTP request to the CKAN instance configured within * the constructor, returning the entire contents of the response. * * @param path The URL path to make the POST request to * @param data The data to be posted to the URL * @returns The String contents of the response * @throws A CKANException if the request fails */ protected String post(String path, String data) throws CKANException { URL url = null; try { url = new URL(this.m_host + ":" + this.m_port + path); } catch (MalformedURLException mue) { System.err.println(mue); return null; } String body = ""; BasicClientConnectionManager bccm = null; ClientConnectionManager cm = null; try { /***********************************************************************/ SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { System.out.println("getAcceptedIssuers ============="); return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { System.out.println("checkClientTrusted ============="); } public void checkServerTrusted(X509Certificate[] certs, String authType) { System.out.println("checkServerTrusted ============="); } } }, new SecureRandom()); SSLSocketFactory sf = new SSLSocketFactory(sslContext); Scheme httpsScheme = new Scheme("https", 443, sf); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); //bccm = new BasicClientConnectionManager(schemeRegistry); // apache HttpClient version >4.2 should use BasicClientConnectionManager cm = new SingleClientConnManager(schemeRegistry); /***********************************************************************/ } catch (KeyManagementException kme) { System.out.println("Con ex: " + kme.getMessage()); } catch (NoSuchAlgorithmException nsae) { System.out.println("Con ex: " + nsae.getMessage()); } //HttpClient httpclient = new DefaultHttpClient(cm); HttpClient httpclient = new DefaultHttpClient(); try { HttpPost postRequest = new HttpPost(url.toString()); postRequest.setHeader("X-CKAN-API-Key", this._apikey); StringEntity input = new StringEntity(data); input.setContentType("application/json"); postRequest.setEntity(input); HttpResponse response = httpclient.execute(postRequest); int statusCode = response.getStatusLine().getStatusCode(); BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String line = ""; while ((line = br.readLine()) != null) { body += line; } } catch (IOException ioe) { System.out.println(ioe); } finally { httpclient.getConnectionManager().shutdown(); } return body; }
From source file:com.villemos.ispace.webster.WebsterProducer.java
public void process(Exchange exchange) throws Exception { /** Always ignore authentication protocol errors. */ if (ignoreAuthenticationFailure) { SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom()); SchemeRegistry schemeRegistry = new SchemeRegistry(); SSLSocketFactory sf = new SSLSocketFactory(sslContext); Scheme httpsScheme = new Scheme("https", sf, 443); schemeRegistry.register(httpsScheme); SocketFactory sfa = new PlainSocketFactory(); Scheme httpScheme = new Scheme("http", sfa, 80); schemeRegistry.register(httpScheme); HttpParams params = new BasicHttpParams(); ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry); client = new DefaultHttpClient(cm, params); } else {//from www. j a v a2s. c o m client = new DefaultHttpClient(); } String proxyHost = getWebsterEndpoint().getProxyHost(); Integer proxyPort = getWebsterEndpoint().getProxyPort(); if (proxyHost != null && proxyPort != null) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } else { ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); client.setRoutePlanner(routePlanner); } /** The target location may demand authentication. We setup preemptive authentication. */ if (getWebsterEndpoint().getAuthenticationUser() != null && getWebsterEndpoint().getAuthenticationPassword() != null) { client.getCredentialsProvider().setCredentials( new AuthScope(getWebsterEndpoint().getDomain(), getWebsterEndpoint().getPort()), new UsernamePasswordCredentials(getWebsterEndpoint().getAuthenticationUser(), getWebsterEndpoint().getAuthenticationPassword())); } /** Set default cookie policy and store. Can be overridden for a specific method using for example; * method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); */ client.setCookieStore(cookieStore); client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); String uriStr = getWebsterEndpoint().getProtocol() + "://" + getWebsterEndpoint().getDomain() + "/" + getWebsterEndpoint().getPath(); if (getWebsterEndpoint().getPort() != 80) { uriStr += ":" + getWebsterEndpoint().getPort() + "/" + getWebsterEndpoint().getPath(); } /** Break the query into its elements and search for each. */ for (String word : ((String) exchange.getIn().getHeader(SolrOptions.query)).split("\\s+")) { uriStr += "/" + word; URI uri = new URI(uriStr); if (getWebsterEndpoint().getPort() != 80) { target = new HttpHost(getWebsterEndpoint().getDomain(), getWebsterEndpoint().getPort(), getWebsterEndpoint().getProtocol()); } else { target = new HttpHost(getWebsterEndpoint().getDomain()); } localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpUriRequest method = new HttpGet(uri); HttpResponse response = client.execute(target, method, localContext); if (response.getStatusLine().getStatusCode() == 200) { /** Extract result. */ String page = HttpClientConfigurer.readFully(response.getEntity().getContent()); ResultSet set = new ResultSet(); Matcher matcher = pattern.matcher(page); if (matcher.find()) { String result = matcher.group(1).replaceAll("\\<.*?\\>", "").replaceAll("\\s+", " "); /** Create ResultSet*/ InformationObject io = new InformationObject(); io.hasUri = uriStr; io.fromSource = "Webster"; io.hasTitle = "Webster definition of '" + word + "'."; io.ofEntityType = "Definition"; io.ofMimeType = "text/html"; io.withRawText = result; io.score = 20; set.informationobjects.add(io); } matcher = spellPattern.matcher(page); if (matcher.find()) { String result = matcher.group(1); String[] elements = result.split("<li><a href=.*?>"); for (String element : elements) { if (element.trim().equals("") == false) { set.suggestions .add(new Suggestion(word, element.replaceAll("<.*?>", "").trim(), "Webster")); } } } if (exchange.getIn().getHeader(SolrOptions.stream) != null) { for (InformationObject io : set.informationobjects) { Exchange newExchange = new DefaultExchange(endpoint.getCamelContext()); newExchange.getIn().setBody(io); endpoint.getCamelContext().createProducerTemplate() .send((String) exchange.getIn().getHeader(SolrOptions.stream), newExchange); } for (Suggestion suggestion : set.suggestions) { Exchange newExchange = new DefaultExchange(endpoint.getCamelContext()); newExchange.getIn().setBody(suggestion); endpoint.getCamelContext().createProducerTemplate() .send((String) exchange.getIn().getHeader(SolrOptions.stream), newExchange); } } else { exchange.getOut().setBody(set); } } else { HttpEntity entity = response.getEntity(); InputStream instream = entity.getContent(); String page = HttpClientConfigurer.readFully(response.getEntity().getContent()); System.out.println(page); } } }
From source file:com.cloudhopper.httpclient.util.SchemeFactory.java
static public Scheme createDoNotVerifyHttpsScheme() throws NoSuchAlgorithmException, KeyManagementException { TrustManager sslTrustManager = new DoNotVerifySSLCertificateTrustManager(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[] { sslTrustManager }, null); SSLSocketFactory sf = new SSLSocketFactory(sslcontext); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return new Scheme("https", sf, 443); }
From source file:com.appdynamics.openstack.nova.RestClient.java
static HttpClient httpClientWithTrustManager() throws KeyManagementException, NoSuchAlgorithmException { HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); httpClient.getParams().setParameter("http.connection-manager.max-per-host", 1); X509TrustManager tm = new X509TrustManager() { @Override//from w ww . ja v a 2 s. co m public X509Certificate[] getAcceptedIssuers() { // TODO Auto-generated method stub return null; } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } }; SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx); ClientConnectionManager ccm = httpClient.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", ssf, 443)); // Scheme("https", ssf, 443)); return new DefaultHttpClient(ccm, httpClient.getParams()); }
From source file:iristk.speech.nuancecloud.NuanceCloudRecognizerListener.java
@SuppressWarnings("deprecation") private static HttpClient getHttpClient() throws NoSuchAlgorithmException, KeyManagementException { // Standard HTTP parameters HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUseExpectContinue(params, false); // Initialize the HTTP client HttpClient httpclient = new DefaultHttpClient(params); // Initialize/setup SSL TrustManager easyTrustManager = new X509TrustManager() { @Override/* w w w . ja va 2s. co m*/ public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException { } @Override 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 sch = new Scheme("https", sf, 443); httpclient.getConnectionManager().getSchemeRegistry().register(sch); // Return the initialized instance of our httpclient return httpclient; }
From source file:org.frameworkset.spi.remote.http.Client.java
protected static ClientConnectionManager createClientConnectionManager() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, KeyManagementException, UnrecoverableKeyException { SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); ProMap ssls = ApplicationContext.getApplicationContext().getMapProperty("rpc.protocol.http.ssl.client"); ssls = null;//from w w w .j ava 2 s . c o m if (ssls == null) { registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // throw new Exception( // "?ssl? rpc.protocol.http.ssl.server ?org/frameworkset/spi/manager-rpc-http.xml??"); } else { String trustStore_ = ssls.getString("trustStore"); String trustStorePassword = ssls.getString("trustStorePassword"); KeyStore trustStore = SSLHelper.getKeyStore(trustStore_, trustStorePassword); SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore); registry.register(new Scheme("https", socketFactory, 443)); } ClientConnectionManager connManager = null; ClientConnectionManagerFactory factory = null; connManager = new ThreadSafeClientConnManager(params, registry); return connManager; }
From source file:org.cloudsmith.stackhammer.api.client.StackHammerClient.java
@Inject public StackHammerClient(@Named("StackHammer baseUri") String baseUri, @Named("StackHammer credentials") String credentials) { this.baseUri = baseUri; this.credentials = credentials == null ? null : (AUTH_TOKEN + ' ' + credentials); userAgent = USER_AGENT;//from www. j a v a2s.co m httpClient = new DefaultHttpClient(); try { httpClient.getConnectionManager().getSchemeRegistry() .register(new Scheme("https", 443, new SSLSocketFactory(new TrustSelfSignedStrategy()))); } catch (Exception e) { // let's try without that ... } }
From source file:org.wso2.cdm.agent.utils.HTTPConnectorUtils.java
public static HttpClient getCertifiedHttpClient(Context context) { try {//from w w w. j a v a 2 s.co m HttpClient client = null; if (CommonUtilities.SERVER_PROTOCOL.toLowerCase().equals("https://")) { Log.e("", "in"); KeyStore localTrustStore = KeyStore.getInstance("BKS"); InputStream in = context.getResources().openRawResource(R.raw.emm_truststore); localTrustStore.load(in, CommonUtilities.TRUSTSTORE_PASSWORD.toCharArray()); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore); schemeRegistry.register(new Scheme("https", sslSocketFactory, 443)); HttpParams params = new BasicHttpParams(); ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); client = new DefaultHttpClient(cm, params); } else { client = new DefaultHttpClient(); } return client; } catch (Exception e) { return null; } }