List of usage examples for javax.net.ssl X509TrustManager X509TrustManager
X509TrustManager
From source file:edu.duke.cabig.c3pr.webservice.integration.SubjectMassCreator.java
private static void disableSSLVerification() { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }/*from w w w .j av a 2 s . com*/ public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } com.sun.net.ssl.HostnameVerifier hv = new com.sun.net.ssl.HostnameVerifier() { public boolean verify(String urlHostname, String certHostname) { return true; } }; com.sun.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(hv); HostnameVerifier hv2 = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(hv2); }
From source file:org.binding.openhab.samsungac.communicator.AirConditioner.java
private void connect() throws Exception { if (isConnected()) { return;/*from w w w . ja v a 2 s. c o m*/ } else { logger.debug("Disconnected so we'll try again"); disconnect(); } if (CERTIFICATE_FILE_NAME != null && new File(CERTIFICATE_FILE_NAME).isFile()) { if (CERTIFICATE_PASSWORD == null) { CERTIFICATE_PASSWORD = ""; } try { SSLClient client = new SSLClient(); client.addTrustMaterial(TrustMaterial.DEFAULT); client.setCheckHostname(false); client.setKeyMaterial(new KeyMaterial(CERTIFICATE_FILE_NAME, CERTIFICATE_PASSWORD.toCharArray())); client.setConnectTimeout(10000); socket = (SSLSocket) client.createSocket(IP, PORT); socket.setSoTimeout(30000); socket.startHandshake(); } catch (Exception e) { throw new Exception("Could not connect using certificate: " + CERTIFICATE_FILE_NAME, e); } } else { try { SSLContext ctx = SSLContext.getInstance("TLS"); final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } } }; ctx.init(null, trustAllCerts, null); socket = (SSLSocket) ctx.getSocketFactory().createSocket(IP, PORT); socket.setSoTimeout(10000); socket.startHandshake(); } catch (Exception e) { throw new Exception("Cannot connect to " + IP + ":" + PORT, e); } } handleResponse(); }
From source file:org.dasein.cloud.google.HttpsConnection.java
public static String getJSON(String iss, String p12File) throws Exception { System.out.println("ISS : " + iss); System.out.println("P12File : " + p12File); HttpClient client = new DefaultHttpClient(); List formparams = new ArrayList(); formparams.add(new BasicNameValuePair("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer")); formparams.add(new BasicNameValuePair("assertion", GenerateToken.getToken(iss, p12File))); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); // HttpClient client1 = new HttpClient(); String url = "https://accounts.google.com/o/oauth2/token"; // System.out.println(url); // PostMethod pm = new PostMethod(url); // pm.addRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // pm.addRequestHeader("Host", "accounts.google.com"); //// pm.addRequestHeader("Host", "accounts.google.com"); // pm.addParameter("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"); // pm.addParameter("assertion", GenerateToken.getData()); //// System.out.println(C.getData()); ////from w w w .ja v a2 s.c o m // int statusCode = client1.executeMethod(pm); HttpPost httppost = new HttpPost(url); httppost.addHeader("Content-Type", "application/x-www-form-urlencoded"); httppost.setEntity(entity); HttpResponse httpResponse1 = client.execute(httppost); int s1 = httpResponse1.getStatusLine().getStatusCode(); if (s1 == HttpStatus.SC_OK) { try { // InputStream in = getResponseBody(pm); InputStream in = httpResponse1.getEntity().getContent(); writeToFile(in, "D:\\google_out.txt"); System.out.println(printFile("D:\\google_out.txt")); } catch (Exception e) { System.out.println("No response body !"); } } JSONObject obj1 = new JSONObject(printFile("D:\\google_out.txt")); String access_token = obj1.getString("access_token"); String token_type = obj1.getString("token_type"); String expires_in = obj1.getString("expires_in"); String resource = "instances"; url = "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-east1-a/" + resource + "?access_token=" + access_token + "&token_type=Bearer&expires_in=3600"; String str = "{" + "\"image\": \"https://www.googleapis.com/compute/v1beta14/projects/google/global/images/gcel-10-04-v20130104\"," + "\"machineType\": \"https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/global/machineTypes/n1-standard-1\"," + "\"name\": \"trial\"," + "\"zone\": \"https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-east1-a/\"," + "\"networkInterfaces\": [ { \"network\": \"https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/networks/default\" } ]," + "\"disks\": [ { \"type\": \"EPHEMERAL\", \"deleteOnTerminate\": true } ], \"metadata\": { \"items\": [ ], \"kind\": \"compute#metadata\" }}"; System.out.println(str); JSONObject json = new JSONObject(str); System.out.println("POST Methods : " + url); StringEntity se = new StringEntity(str); JSONObject json1 = new JSONObject(); json1.put("image", "https://www.googleapis.com/compute/v1beta14/projects/google/global/images/gcel-10-04-v20130104"); json1.put("machineType", "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/global/machineTypes/n1-standard-1"); json1.put("name", "trial"); json1.put("zone", "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-east1-a/"); //json1.put("image", "https://www.googleapis.com/compute/v1beta13/projects/google/images/ubuntu-10-04-v20120621"); System.out.println(" JSON 1 : " + json.toString() + " \n JSON 2 : " + json1.toString()); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("json", str)); // // JSONObject jsonPayload = null; // JSONObject obj = new JSONObject(); // // try { // obj.put("name", "vinotrial"); // obj.put("IPv4Range", "192.0.0.0/16"); // obj.put("description", "wrwer"); // // } catch (Exception e) { // // } /* JSONObject jsonPayload = null; JSONObject obj = new JSONObject(); try { obj.put("name", "testCreateStandardFirewall1734".toLowerCase()); obj.put("description", "SSH allowed from anywhere"); obj.put("network", "https://www.googleapis.com/compute/v1beta13/projects/enstratus.com:enstratus-dev/networks/default"); JSONArray sranges = new JSONArray(); JSONArray allowed = new JSONArray(); JSONObject allowedtemp = new JSONObject(); JSONArray ports = new JSONArray(); allowedtemp.put("IPProtocol", "tcp"); ports.put("22"); allowedtemp.put("ports", ports); allowed.put(allowedtemp); // // JSONObject allowedtemp1 = new JSONObject(); // JSONArray ports1 = new JSONArray(); // allowedtemp1.put("IPProtocol", "udp"); // ports1.put("1-65535"); // allowedtemp1.put("ports", ports1); // allowed.put(allowedtemp1); // // // // JSONObject allowedtemp2 = new JSONObject(); // // allowedtemp2.put("IPProtocol", "icmp"); // // allowed.put(allowedtemp2); sranges.put("0.0.0.0/0"); obj.put("sourceRanges", sranges); obj.put("allowed", allowed); } catch (Exception e) { } */ //UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(formparams1, "UTF-8"); System.out.println("Creating an instance"); HttpPost httppost1 = new HttpPost(url); httppost1.setHeader("Content-type", "application/json"); //httppost1.addHeader("X-JavaScript-User-Agent", "trov"); //httppost1.setEntity(se); // httppost1.setEntity(new UrlEncodedFormEntity(nameValuePairs)); System.out.println("payload:" + json1.toString()); System.out.println("url:" + url); StringEntity se1 = new StringEntity(json1.toString()); se1.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); httppost1.setEntity(se1); // HttpClient base = new DefaultHttpClient(); SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", ssf, 443)); HttpClient client1 = new DefaultHttpClient(ccm); //HttpClient client1 = new DefaultHttpClient(); HttpResponse httpResponse2 = client1.execute(httppost1); int s2 = httpResponse2.getStatusLine().getStatusCode(); if (s2 == HttpStatus.SC_OK) { try { // InputStream in = getResponseBody(pm); InputStream in = httpResponse2.getEntity().getContent(); writeToFile(in, "D:\\google_out.txt"); System.out.println(printFile("D:\\google_out.txt")); } catch (Exception e) { System.out.println("No response body !"); } } else { System.out.println("Instance creation failed with error status " + s2); InputStream in = httpResponse2.getEntity().getContent(); writeToFile(in, "D:\\google_out.txt"); System.out.println(printFile("D:\\google_out.txt")); } String[] Zone = { "europe-west1-a", "europe-west1-b", "us-central1-a", "us-central1-b", "us-central2-a", "us-east1-a" }; for (String zone : Zone) { // { HttpClient client3 = new DefaultHttpClient(); resource = "instances"; System.out.println("listing the instances !"); // url= "https://www.googleapis.com/compute/v1beta13/projects/google/kernels?access_token=" + access_token + "&token_type=Bearer&expires_in=3600" ; url = "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-central1-a/" + resource + "?access_token=" + access_token + "&token_type=Bearer&expires_in=3600"; // url = "https://www.googleapis.com/compute/v1beta13/projects/enstratus.com:enstratus-dev?access_token=" + access_token + "&token_type=Bearer&expires_in=3600" ; // url = "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-east1-a/instances?access_token=" + access_token + "&token_type=Bearer&expires_in=3600" ; System.out.println("url : -----------" + url); JSONArray items = new JSONArray(); HttpGet method = new HttpGet(url); HttpResponse httpResponse = client3.execute(method); int s = httpResponse.getStatusLine().getStatusCode(); if (s == HttpStatus.SC_OK) { try { System.out.println("\nResponse from Server : "); //InputStream in = getResponseBody(gm); InputStream in = httpResponse.getEntity().getContent(); writeToFile(in, "D:\\calendar_out.txt"); String str1 = printFile("D:\\calendar_out.txt"); System.out.println(str1); JSONObject jsonO = new JSONObject(str1); items = (JSONArray) jsonO.get("items"); // return printFile("D:\\calendar_out.txt"); } catch (Exception e) { System.out.println("No response body !" + e.getLocalizedMessage()); } } else System.out.println(httpResponse); for (int i = 0; i < items.length(); i++) { JSONObject item = (JSONObject) items.get(i); String name = null; if (item.has("name")) name = (String) item.get("name"); //System.out.println("instance : " + name); if (!name.contains("default")) { System.out.println("Deleting the instance " + name); url = "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-central1-a/" + resource + "/" + name + "?access_token=" + access_token + "&token_type=Bearer&expires_in=3600"; System.out.println("url : " + url); HttpDelete delMethod = new HttpDelete(url); HttpResponse httpResponse3 = client.execute(delMethod); int s3 = httpResponse3.getStatusLine().getStatusCode(); if (s3 == HttpStatus.SC_OK) { try { System.out.println("\nResponse from Server : "); //InputStream in = getResponseBody(gm); InputStream in = httpResponse3.getEntity().getContent(); writeToFile(in, "D:\\calendar_out.txt"); System.out.println(printFile("D:\\calendar_out.txt")); // return printFile("D:\\calendar_out.txt"); } catch (Exception e) { System.out.println("No response body !"); } } else { System.out.println("Deleting failed with status : " + s3); try { InputStream in = httpResponse3.getEntity().getContent(); writeToFile(in, "D:\\calendar_out.txt"); System.out.println(printFile("D:\\calendar_out.txt")); } catch (Exception e) { } } } } // https://www.googleapis.com/compute/v1beta13/projects/enstratus.com%3Aenstratus-dev/instances/trial // GetMethod gm = new GetMethod(url); // HttpMethodParams params = new HttpMethodParams(); //// params.setParameter("calendarId", "vidhyanallasamy%40gmail.com"); // gm.setParams(params); // // statusCode = client1.executeMethod(gm); // System.out.println("\nStatus Code : " + statusCode); // // try { // System.out.println("\nResponse from Server : "); // InputStream in = getResponseBody(gm); // writeToFile(in, "D:\\calendar_out.txt"); // System.out.println(printFile("D:\\calendar_out.txt")); // } catch (Exception e) { // System.out.println("No response body !"); // }\ } return null; }
From source file:org.apache.maven.report.projectinfo.ProjectInfoReportUtils.java
/** * @param url not null//from w w w .j ava 2s . co m * @param project not null * @param settings not null * @return the url connection with auth if required. Don't check the certificate if SSL scheme. * @throws IOException if any */ private static URLConnection getURLConnection(URL url, MavenProject project, Settings settings) throws IOException { URLConnection conn = url.openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); // conn authorization if (settings.getServers() != null && !settings.getServers().isEmpty() && project != null && project.getDistributionManagement() != null && (project.getDistributionManagement().getRepository() != null || project.getDistributionManagement().getSnapshotRepository() != null) && (StringUtils.isNotEmpty(project.getDistributionManagement().getRepository().getUrl()) || StringUtils.isNotEmpty( project.getDistributionManagement().getSnapshotRepository().getUrl()))) { Server server = null; if (url.toString().contains(project.getDistributionManagement().getRepository().getUrl())) { server = settings.getServer(project.getDistributionManagement().getRepository().getId()); } if (server == null && url.toString() .contains(project.getDistributionManagement().getSnapshotRepository().getUrl())) { server = settings.getServer(project.getDistributionManagement().getSnapshotRepository().getId()); } if (server != null && StringUtils.isNotEmpty(server.getUsername()) && StringUtils.isNotEmpty(server.getPassword())) { String up = server.getUsername().trim() + ":" + server.getPassword().trim(); String upEncoded = new String(Base64.encodeBase64Chunked(up.getBytes())).trim(); conn.setRequestProperty("Authorization", "Basic " + upEncoded); } } if (conn instanceof HttpsURLConnection) { HostnameVerifier hostnameverifier = new HostnameVerifier() { /** {@inheritDoc} */ public boolean verify(String urlHostName, SSLSession session) { return true; } }; ((HttpsURLConnection) conn).setHostnameVerifier(hostnameverifier); TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { /** {@inheritDoc} */ public void checkClientTrusted(final X509Certificate[] chain, final String authType) { } /** {@inheritDoc} */ public void checkServerTrusted(final X509Certificate[] chain, final String authType) { } /** {@inheritDoc} */ public X509Certificate[] getAcceptedIssuers() { return null; } } }; try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new SecureRandom()); SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory); } catch (NoSuchAlgorithmException e1) { // ignore } catch (KeyManagementException e) { // ignore } } return conn; }
From source file:org.neo4j.harness.InProcessBuilderTest.java
private void trustAllSSLCerts() throws NoSuchAlgorithmException, KeyManagementException { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override//from www.j a v a 2s. com public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); }
From source file:org.sandrob.android.net.http.HttpsConnection.java
/** * //w ww. j a v a 2 s . c om * * @param sessionDir directory to cache SSL sessions * @param req request that call this function */ public void initializeEngine(File sessionDir, Request req) { if (mSslSocketFactory == null) { String certificateFullPathName = null; String keyStoreType = "PKCS12"; String keyStoreProvider = "BC"; String certificatePassword = null; try { SSLClientSessionCache cache = null; KeyManager[] keyManagers = null; KeyStore keyStore = null; if (sessionDir != null) { Log.d("HttpsConnection", "Caching SSL sessions in " + sessionDir + "."); cache = FileClientSessionCache.usingDirectory(sessionDir); } // Inform the user if we need ssl client settings if (true) { synchronized (mSuspendLock) { mSuspended = true; } // don't hold the lock while calling out to the event handler boolean canHandle = req.getEventHandler().handleSslClientSetingsRequest(); if (!canHandle) { throw new IOException("failed to handle ssl client settings "); } synchronized (mSuspendLock) { if (mSuspended) { try { // Put a limit on how long we are waiting; if the timeout // expires (which should never happen unless you choose // to ignore the SSL error dialog for a very long time), // we wake up the thread and abort the request. This is // to prevent us from stalling the network if things go // very bad. mSuspendLock.wait(10 * 60 * 1000); if (mSuspended) { // mSuspended is true if we have not had a chance to // restart the connection yet (ie, the wait timeout // has expired) mSuspended = false; mAborted = true; if (HttpLog.LOGV) { HttpLog.v("HttpsConnection.openConnection():" + " SSL timeout expired and request was cancelled!!!"); } } } catch (InterruptedException e) { // ignore } } if (mAborted) { // The user decided not to use this unverified connection // so close it immediately. throw new SSLConnectionClosedByUserException("connection closed by the user"); } if (mSslClientCertificate != null) { // we have some data about client certificate certificateFullPathName = mSslClientCertificate.getCertificateFileName(); certificatePassword = mSslClientCertificate.getCertificateFilePassword(); } } } SSLContextImpl sslContext = new SSLContextImpl(); //SSLContext sslContext = SSLContext.getInstance("TLS"); if (certificateFullPathName != null && certificatePassword != null) { File certFile = new File(certificateFullPathName); if (certFile.exists()) { keyStore = KeyStore.getInstance(keyStoreType, keyStoreProvider); keyStore.load(new FileInputStream(new File(certificateFullPathName)), certificatePassword.toCharArray()); String kmfa = KeyManagerFactory.getDefaultAlgorithm(); KeyManagerFactory kmf = KeyManagerFactory.getInstance(kmfa); kmf.init(keyStore, certificatePassword.toCharArray()); keyManagers = kmf.getKeyManagers(); } } // here, trust managers is a single trust-all manager TrustManager[] trustManagers = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; sslContext.engineInit(keyManagers, trustManagers, null, cache, null); //sslContext.init(keyManagers, trustManagers, null); synchronized (HttpsConnection.class) { mSslSocketFactory = sslContext.engineGetSocketFactory(); //mSslSocketFactory = sslContext.getSocketFactory(); } } catch (KeyManagementException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } }
From source file:io.apiman.gateway.platforms.servlet.connectors.ssl.SSLSessionStrategyFactory.java
/** * <strong><em>Do not use in production</em></strong> * <p>//from w w w. j av a2 s . co m * Returns an SSLSessionStrategy that trusts any Certificate. * <p> * Naturally, this is vulnerable to a raft of MIITM and forgery attacks, so users should exercise extreme * caution and only use it for development purposes. * * @return the ssl strategy */ public static SSLSessionStrategy buildUnsafe() { System.err.println("ATTENTION: SSLSessionStrategy will trust *any* certificate." //$NON-NLS-1$ + " This is extremely unsafe for production. Caveat utilitor!"); //$NON-NLS-1$ try { SSLContext sslContext = SSLContext.getInstance("TLS"); //$NON-NLS-1$ // This accepts anything. sslContext.init(null, new X509TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }, new SecureRandom()); return new SSLSessionStrategy(ALLOW_ANY, sslContext.getSocketFactory()); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.sckftr.android.utils.net.Network.java
private static SSLSocketFactory getAllHostsValidSocketFactory() throws NoSuchAlgorithmException, KeyManagementException { if (sAllHostsValidSocketFactory == null) { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; }//from w ww . j av a 2 s . co m public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); sAllHostsValidSocketFactory = sc.getSocketFactory(); } return sAllHostsValidSocketFactory; }
From source file:com.baidu.qa.service.test.client.SoapReqImpl.java
private static String sendSoapViaHttps(String hosturl, String ip, int port, String action, String method, String xml) {//ww w . j a v a2 s . c o m String reqURL = "https://" + ip + ":" + port + action; // Map<String, String> params = null; long responseLength = 0; // ? String responseContent = null; // ? HttpClient httpClient = new DefaultHttpClient(); // httpClient httpClient.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000); X509TrustManager xtm = new X509TrustManager() { // TrustManager public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; try { // TLS1.0SSL3.0??TLSSSL?SSLContext SSLContext ctx = SSLContext.getInstance("TLS"); // TrustManager??TrustManager?SSLSocket ctx.init(null, new TrustManager[] { xtm }, null); // SSLSocketFactory SSLSocketFactory socketFactory = new SSLSocketFactory(ctx); // SchemeRegistrySSLSocketFactoryHttpClient httpClient.getConnectionManager().getSchemeRegistry() .register(new Scheme("https", port, socketFactory)); HttpPost httpPost = new HttpPost(reqURL); // HttpPost // add the 3 headers below httpPost.addHeader("Accept-Encoding", "gzip,deflate"); httpPost.addHeader("SOAPAction", hosturl + action + method);// SOAP action httpPost.addHeader("uuid", "itest");// for editor token of DR-Api // HttpEntity requestBody = new // ByteArrayEntity(xml.getBytes("UTF-8"));// TODO byte[] b = xml.getBytes("UTF-8"); // must be UTF-8 InputStream is = new ByteArrayInputStream(b, 0, b.length); HttpEntity requestBody = new InputStreamEntity(is, b.length, ContentType.create("text/xml;charset=UTF-8"));// must be // UTF-8 httpPost.setEntity(requestBody); log.info(">> Request URI: " + httpPost.getRequestLine().getUri()); HttpResponse response = httpClient.execute(httpPost); // POST HttpEntity entity = response.getEntity(); // ?? if (null != entity) { responseLength = entity.getContentLength(); String contentEncoding = null; Header ce = response.getEntity().getContentEncoding(); if (ce != null) { contentEncoding = ce.getValue(); } if (contentEncoding != null && contentEncoding.indexOf("gzip") != -1) { GZIPInputStream gzipin = new GZIPInputStream(response.getEntity().getContent()); Scanner in = new Scanner(new InputStreamReader(gzipin, "UTF-8")); StringBuilder sb = new StringBuilder(); while (in.hasNextLine()) { sb.append(in.nextLine()).append(System.getProperty("line.separator")); } responseContent = sb.toString(); } else { responseContent = EntityUtils.toString(response.getEntity(), "UTF-8"); } EntityUtils.consume(entity); // Consume response content } log.info("?: " + httpPost.getURI()); log.info("??: " + response.getStatusLine()); log.info("?: " + responseLength); log.info("?: " + responseContent); } catch (KeyManagementException e) { log.error(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { log.error(e.getMessage(), e); } catch (UnsupportedEncodingException e) { log.error(e.getMessage(), e); } catch (ClientProtocolException e) { log.error(e.getMessage(), e); } catch (ParseException e) { log.error(e.getMessage(), e); } catch (IOException e) { log.error(e.getMessage(), e); } finally { httpClient.getConnectionManager().shutdown(); // ,? return responseContent; } }
From source file:com.flipzu.flipzu.FlipInterface.java
/** * Trust every server - dont check for any certificate *///from w w w .jav a 2 s .co m private static void trustAllHosts() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[] {}; } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { Log.e(TAG, "trustAllHosts ERROR", e.getCause()); } }