private static HttpURLConnection createConnection(URL url, Map<String, String> header) throws ProtocolException { HttpURLConnection httpURLConnection = null; try { httpURLConnection = (HttpURLConnection) url.openConnection(); } catch (IOException var4) { var4.printStackTrace(); return null; } httpURLConnection.setConnectTimeout(CONNECTION_TIME_OUT); httpURLConnection.setReadTimeout(READ_TIME_OUT); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setUseCaches(false); Iterator<String> headerIterator = header.keySet().iterator(); while (headerIterator.hasNext()) { String key = headerIterator.next(); httpURLConnection.setRequestProperty(key, header.get(key)); } httpURLConnection.setRequestMethod("POST"); if ("https".equalsIgnoreCase(url.getProtocol())) { HttpsURLConnection husn = (HttpsURLConnection) httpURLConnection; husn.setSSLSocketFactory(new BaseHttpSSLSocketFactory()); husn.setHostnameVerifier(new BaseHttpSSLSocketFactory.TrustAnyHostnameVerifier()); return husn; } else { return httpURLConnection; } }
/** * Create a new BeeswaxServiceImpl. * * @param dtHost The Hue host (ip or hostname). * @param dtPort The port Desktop runs on. * @param dtHttps Whether Desktop is running https. */ public BeeswaxServiceImpl(String dtHost, int dtPort, boolean dtHttps) { LogContext.initLogCapture(); this.executor = Executors.newCachedThreadPool(new NamingThreadFactory("Beeswax-%d")); this.runningQueries = new ConcurrentHashMap<String, RunningQueryState>(); String protocol; if (dtHttps) { protocol = "https"; try { // Disable SSL verification. HUE cert may be signed by untrusted CA. SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init( null, new DummyX509TrustManager[] {new DummyX509TrustManager()}, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory()); } catch (NoSuchAlgorithmException ex) { LOG.warn("Failed to disable SSL certificate check " + ex); } catch (KeyManagementException ex) { LOG.warn("Failed to disable SSL certificate check " + ex); } DummyHostnameVerifier dummy = new DummyHostnameVerifier(); HttpsURLConnection.setDefaultHostnameVerifier(dummy); } else { protocol = "http"; } this.notifyUrl = protocol + "://" + dtHost + ":" + dtPort + NOTIFY_URL_BASE; // A daemon thread that periodically evict stale RunningQueryState objects Thread evicter = new Thread( new Runnable() { @Override public void run() { while (true) { long now = System.currentTimeMillis(); for (Map.Entry<String, RunningQueryState> entry : runningQueries.entrySet()) { RunningQueryState rqState = entry.getValue(); if (rqState.getAtime() + RUNNING_QUERY_LIFETIME < now) { String id = entry.getKey(); runningQueries.remove(id); LOG.debug("Removed " + rqState.toString()); Thread.yield(); // be nice } } LogContext.garbageCollect(RUNNING_QUERY_LIFETIME); long wakeup = now + EVICTION_INTERVAL; while (System.currentTimeMillis() < wakeup) { try { Thread.sleep(EVICTION_INTERVAL); } catch (InterruptedException e) { } } } } }, "Evicter"); evicter.setDaemon(true); evicter.start(); }
/* package */ String loadNetwork(String url) { InputStreamReader isr = null; BufferedReader br = null; try { HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection(); isr = new InputStreamReader(con.getInputStream()); br = new BufferedReader(isr); String line = null; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line); } return sb.toString(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (isr != null) { try { isr.close(); } catch (Exception e) { e.printStackTrace(); } } if (br != null) { try { br.close(); } catch (Exception e) { e.printStackTrace(); } } } return null; }
public User getUserFromSocNet() { try { String methodString = VKOAuth2Details.methodUri + "users.get?user_ids=" + userId + "&fields=city,sex,bdate&v=5.28&access_token=" + accessToken + "&lang=ua"; URL newUrl = new URL(methodString); HttpsURLConnection con = (HttpsURLConnection) newUrl.openConnection(); InputStream ins = con.getInputStream(); InputStreamReader newIsr = new InputStreamReader(ins, "UTF-8"); JSONParser parser = new JSONParser(); JSONObject response = (JSONObject) parser.parse(newIsr); JSONArray jsonUsers = (JSONArray) response.get("response"); JSONObject jsonUser = (JSONObject) jsonUsers.get(0); User user = new User(); user.setSocialId("vk" + userId); user.setEmail(email); user.setFirstName(jsonUser.get("first_name").toString()); user.setLastName(jsonUser.get("last_name").toString()); return user; } catch (Exception e) { e.printStackTrace(); } return null; }
public String getContent(URL url, boolean altercookies) { String s = ""; try { HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestProperty("Cookie", cookies); // Retain our sessoin BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); String input; while ((input = br.readLine()) != null) { s += input + "\n"; } br.close(); StringBuilder sb = new StringBuilder(); // find the cookies in the response header from the first request List<String> cookie = con.getHeaderFields().get("Set-Cookie"); if (cookie != null) { for (String cooki : cookie) { if (sb.length() > 0) { sb.append("; "); } // only want the first part of the cookie header that has the value String value = cooki.split(";")[0]; sb.append(value); } } if (altercookies) cookies = sb.toString(); } catch (Exception e) { e.printStackTrace(); } return s; }
@Override protected HttpURLConnection openConnection(String path, String query) throws IOException { query = addDelegationTokenParam(query); final URL url = new URL("https", nnAddr.getHostName(), nnAddr.getPort(), path + '?' + query); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); // bypass hostname verification try { conn.setHostnameVerifier(new DummyHostnameVerifier()); conn.setRequestMethod("GET"); conn.connect(); } catch (IOException ioe) { throwIOExceptionFromConnection(conn, ioe); } // check cert expiration date final int warnDays = ExpWarnDays; if (warnDays > 0) { // make sure only check once ExpWarnDays = 0; long expTimeThreshold = warnDays * MM_SECONDS_PER_DAY + System.currentTimeMillis(); X509Certificate[] clientCerts = (X509Certificate[]) conn.getLocalCertificates(); if (clientCerts != null) { for (X509Certificate cert : clientCerts) { long expTime = cert.getNotAfter().getTime(); if (expTime < expTimeThreshold) { StringBuilder sb = new StringBuilder(); sb.append("\n Client certificate " + cert.getSubjectX500Principal().getName()); int dayOffSet = (int) ((expTime - System.currentTimeMillis()) / MM_SECONDS_PER_DAY); sb.append(" have " + dayOffSet + " days to expire"); LOG.warn(sb.toString()); } } } } return (HttpURLConnection) conn; }
public User getUserFromSocNet() { try { String methodString = FacebookOAuth2Details.methodUri + "me?access_token=" + accessToken; URL newUrl = new URL(methodString); HttpsURLConnection con = (HttpsURLConnection) newUrl.openConnection(); InputStream ins = con.getInputStream(); InputStreamReader newIsr = new InputStreamReader(ins, "UTF-8"); JSONParser parser = new JSONParser(); JSONObject jsonUser = (JSONObject) parser.parse(newIsr); userId = jsonUser.get("id").toString(); User user = new User(); user.setSocialId("fb" + userId); user.setFirstName(jsonUser.get("first_name").toString()); user.setLastName(jsonUser.get("last_name").toString()); if (jsonUser.get("email") != null) { user.setEmail(jsonUser.get("email").toString()); } return user; } catch (Exception e) { e.printStackTrace(); } return null; }
public String requestBearerToken() throws IOException { HttpsURLConnection connection = null; String encodedCredentials = encodeKeys(BUNDLE.getString("twt.client_id"), BUNDLE.getString("twt.secret")); String endPointUrl = "https://api.twitter.com/oauth2/token"; try { HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse(); response.setHeader("Host", "api.twitter.com"); response.setHeader("User-Agent", "Iclub"); response.setHeader("Authorization", "Basic " + encodedCredentials); response.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); response.setHeader("Content-Length", "29"); ServletOutputStream fdsaf = response.getOutputStream(); fdsaf.write("grant_type=client_credentials".getBytes()); fdsaf.close(); response.sendRedirect(endPointUrl); return new String(); } catch (MalformedURLException e) { throw new IOException("Invalid endpoint URL specified.", e); } finally { if (connection != null) { connection.disconnect(); } } }
{ TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) {} public void checkServerTrusted(X509Certificate[] certs, String authType) {} } }; SSLContext sc = null; try { sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HostnameVerifier allHostsValid = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); }
private String getHttpsCertificateInformation(HttpsURLConnection con) { if (con != null) { StringBuilder sb = new StringBuilder(); try { sb.append("\nResponse Code : "); sb.append(con.getResponseCode()); sb.append("\nCipher Suite : "); sb.append(con.getCipherSuite()); sb.append("\n"); Certificate[] certs = con.getServerCertificates(); for (Certificate cert : certs) { sb.append("\nCert Type : "); sb.append(cert.getType()); sb.append("\nCert Hash Code : "); sb.append(cert.hashCode()); sb.append("\nCert Public Key Algorithm : "); sb.append(cert.getPublicKey().getAlgorithm()); sb.append("\nCert Public Key Format : "); sb.append(cert.getPublicKey().getFormat()); sb.append("\n"); } } catch (IOException e) { return "Error while retrieving certificate information: " + e.getMessage(); } return sb.toString(); } return "Given connection was null!"; }
// Get data given REST URL public String getData(String uri) { BufferedReader reader = null; try { URL url = new URL(uri); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestMethod("GET"); StringBuilder sb = new StringBuilder(); reader = new BufferedReader(new InputStreamReader(con.getInputStream())); String line; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } return sb.toString(); } catch (Exception e) { e.printStackTrace(); return null; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); return null; } } } }
/** Creates the Activity and registers a MemorizingTrustManager. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.mtmexample); // set up gui elements findViewById(R.id.connect).setOnClickListener(this); content = (TextView) findViewById(R.id.content); urlinput = (EditText) findViewById(R.id.url); verifyhost = (CheckBox) findViewById(R.id.verifyhost); // register handler for background thread hdlr = new Handler(); // Here, the MemorizingTrustManager is activated for HTTPS try { // set location of the keystore MemorizingTrustManager.setKeyStoreFile("private", "sslkeys.bks"); // register MemorizingTrustManager for HTTPS SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, MemorizingTrustManager.getInstanceList(this), new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); defaultverifier = HttpsURLConnection.getDefaultHostnameVerifier(); // disable redirects to reduce possible confusion HttpsURLConnection.setFollowRedirects(false); } catch (Exception e) { e.printStackTrace(); } }
public void exec(HttpsCb cb) { try { if (!NetUtil.isConnected()) { ViewInject.toast("找不到网络了..."); return; } } catch (Exception e) { return; } if (mSslContext == null) { try { mSslContext = initCertificate(); } catch (Exception e) { e.printStackTrace(); ViewInject.toast("init ssl failed"); return; } } try { HttpsURLConnection conn = openConnection(); int code = conn.getResponseCode(); MLoger.debug("httpcode-->" + code); if (code == 200 || code == 201) { // 网络请求成功 String data = parseResponse(conn.getInputStream()); MLoger.debug("response data-->" + data); if (cb != null) cb.onResponse(data); } else { MLoger.debug("error httpcode-->" + code); } } catch (Exception e) { e.printStackTrace(); } }
/** 信任所有请求站点 */ private void trustAllHttpsCertificates() { try { javax.net.ssl.X509TrustManager tm = new javax.net.ssl.X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} }; // Create a trust manager that does not validate certificate chains: javax.net.ssl.TrustManager[] trustAllCerts = {tm}; javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, null); javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); javax.net.ssl.HostnameVerifier hv = new javax.net.ssl.HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(hv); } catch (Exception ex) { ex.printStackTrace(); } }
private void assertUrlConnectionSucceeds(SSLContext context, String host, int port) throws Exception { URL url = new URL("https://" + host + ":" + port); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setSSLSocketFactory(context.getSocketFactory()); connection.getInputStream(); }
private HttpUtils(Context context) { // private constructor to prevent instantiation this.context = context; try { // get version number to be set as part of user agent string version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName; } catch (NameNotFoundException e) { } if (Utils.DEV_ENV) { HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); try { TrustManager[] trustManagers = new X509TrustManager[1]; trustManagers[0] = new TrustAllManager(); SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustManagers, null); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception ex) { } } enableHttpResponseCache(); }
/** * Tests whether this client can make an HTTP connection with TLS 1.2. * * @return true if connection is successful. false otherwise. */ public static boolean testTls12Connection() { String protocol = "N/A"; try { SSLContext sslContext = SSLContext.getInstance(getLatestProtocol().toString()); protocol = sslContext.getProtocol(); sslContext.init(null, null, null); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); URL url = new URL("https://" + ENDPOINT); HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection(); httpsConnection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(httpsConnection.getInputStream())); StringBuilder body = new StringBuilder(); while (reader.ready()) { body.append(reader.readLine()); } httpsConnection.disconnect(); if (body.toString().equals("PayPal_Connection_OK")) { return true; } } catch (NoSuchAlgorithmException e) { } catch (UnknownHostException e) { } catch (IOException e) { } catch (KeyManagementException e) { } return false; }
public void taskData() { if ("https".equals(url.getProtocol())) { HttpsURLConnection httpsUrlConnection; try { URLrequestection = url.openConnection(); httpsUrlConnection = (HttpsURLConnection) URLrequestection; httpsUrlConnection.setRequestMethod("GET"); } catch (IOException e) { Log.d( "Exception ", "Message :" + e.getMessage() + "\n StackTrace: " + Log.getStackTraceString(e)); } } else { URLConnection URLrequestection; HttpURLConnection httpUrlConnection; try { URLrequestection = url.openConnection(); httpUrlConnection = (HttpURLConnection) URLrequestection; httpUrlConnection.setRequestMethod("GET"); } catch (IOException e) { Log.d( "Exception ", "Message :" + e.getMessage() + "\n StackTrace: " + Log.getStackTraceString(e)); } } }
public void run() { URLConnection con = null; try { con = url.openConnection(); if ("HTTPS".equalsIgnoreCase(url.getProtocol())) { HttpsURLConnection scon = (HttpsURLConnection) con; try { scon.setSSLSocketFactory(SSLUtil.getSSLSocketFactory(clientCertAlias, trustAnyCert)); HostnameVerifier hv = SSLUtil.getHostnameVerifier(hostCertLevel); if (hv != null) { scon.setHostnameVerifier(hv); } } catch (GeneralSecurityException e) { Debug.logError(e, module); } catch (GenericConfigException e) { Debug.logError(e, module); } } } catch (IOException e) { Debug.logError(e, module); } synchronized (URLConnector.this) { if (timedOut && con != null) { close(con); } else { connection = con; URLConnector.this.notify(); } } }
public void getAccessToken(String code) { try { String accessTokenString = FacebookOAuth2Details.accessTokenUri + "?client_id=" + FacebookOAuth2Details.clientId + "&client_secret=" + FacebookOAuth2Details.clientSecret + "&code=" + code + "&redirect_uri=" + FacebookOAuth2Details.redirectUri; URL myurl = new URL(accessTokenString); HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection(); InputStream ins = con.getInputStream(); InputStreamReader isr = new InputStreamReader(ins, "UTF-8"); JSONParser parser = new JSONParser(); JSONObject jObject = (JSONObject) parser.parse(isr); accessToken = jObject.get("access_token").toString(); } catch (Exception e) { e.printStackTrace(); } }
public static ArrayList<Deal> getDeals( String url, final RequestQueue requestQueue, int startPage, int endPage) { RequestFuture<String> requestFuture = RequestFuture.newFuture(); ArrayList<Deal> deals = new ArrayList<>((endPage - startPage) * 10); String pageParam = null; for (int i = startPage; i < endPage; i++) { String xml = null; pageParam = String.format(L.PAGE_PARAM, i); StringRequest stringRequest = new StringRequest(Request.Method.GET, url + pageParam, requestFuture, requestFuture); try { requestQueue.add(stringRequest); xml = requestFuture.get(30000, TimeUnit.MILLISECONDS); HttpsURLConnection connection = getFeed(url + pageParam); try { deals.addAll(DomXmlMapper.xmlToDeal(connection.getInputStream())); } catch (Exception e) { } finally { connection.disconnect(); Thread.sleep(100); } // deals.addAll(DomXmlMapper.xmlToDeal(xml)); } catch (Exception e) { L.d(TAG, "Error while retreiving feed", e); } } return deals; }
private void print_https_cert(HttpsURLConnection con) { if (con != null) { try { System.out.println("Response Code : " + con.getResponseCode()); System.out.println("Cipher Suite : " + con.getCipherSuite()); System.out.println("\n"); Certificate[] certs = con.getServerCertificates(); for (Certificate cert : certs) { System.out.println("Cert Type : " + cert.getType()); System.out.println("Cert Hash Code : " + cert.hashCode()); System.out.println("Cert Public Key Algorithm : " + cert.getPublicKey().getAlgorithm()); System.out.println("Cert Public Key Format : " + cert.getPublicKey().getFormat()); System.out.println("\n"); } } catch (SSLPeerUnverifiedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
@BeforeClass public static void beforeClass() throws Exception { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) {} @Override public void checkServerTrusted(X509Certificate[] certs, String authType) {} } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HostnameVerifier allHostsValid = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); }
private static void setURLConnectionTrust() { try { HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); SSLContext context = SSLContext.getInstance("TLS"); context.init( null, new X509TrustManager[] { new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; // return null; } } }, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); } catch (Exception e) { // should never happen Log.e("httpmon", "error setting up SSL trust", e); } }
// Get the size of a file from URL response header. public static Long getRemoteSize(String url) { Long remoteSize = (long) 0; HttpURLConnection httpConn = null; HttpsURLConnection httpsConn = null; try { URI uri = new URI(url); if (uri.getScheme().equalsIgnoreCase("http")) { httpConn = (HttpURLConnection) uri.toURL().openConnection(); if (httpConn != null) { String contentLength = httpConn.getHeaderField("content-length"); if (contentLength != null) { remoteSize = Long.parseLong(contentLength); } httpConn.disconnect(); } } else if (uri.getScheme().equalsIgnoreCase("https")) { httpsConn = (HttpsURLConnection) uri.toURL().openConnection(); if (httpsConn != null) { String contentLength = httpsConn.getHeaderField("content-length"); if (contentLength != null) { remoteSize = Long.parseLong(contentLength); } httpsConn.disconnect(); } } } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid URL " + url); } catch (IOException e) { throw new IllegalArgumentException("Unable to establish connection with URL " + url); } return remoteSize; }
/** * HttpUrlConnection 方式,支持指定load-der.crt证书验证,此种方式Android官方建议 * * @throws CertificateException * @throws IOException * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public void initSSL() throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream in = getAssets().open("load-der.crt"); Certificate ca = cf.generateCertificate(in); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(null, null); keystore.setCertificateEntry("ca", ca); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keystore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); URL url = new URL("https://trade3.guosen.com.cn/mtrade/check_version"); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setSSLSocketFactory(context.getSocketFactory()); InputStream input = urlConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); StringBuffer result = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { result.append(line); } Log.e("TTTT", result.toString()); }
public static void trustAllHttpsURLConnection() { // Create a trust manager that does not validate certificate chains if (sslSocketFactory == null) { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) {} @Override public void checkServerTrusted(X509Certificate[] certs, String authType) {} } }; try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustAllCerts, null); sslSocketFactory = sslContext.getSocketFactory(); } catch (Throwable e) { Log.e("trustAllHttpsURLConnection", e.getMessage(), e); } } if (sslSocketFactory != null) { HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory); HttpsURLConnection.setDefaultHostnameVerifier( org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } }
private InputStream processGetRequest(URL url, String keyStore, String keyStorePassword) { SSLSocketFactory sslFactory = getSSLSocketFactory(keyStore, keyStorePassword); HttpsURLConnection con = null; try { con = (HttpsURLConnection) url.openConnection(); } catch (IOException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } con.setSSLSocketFactory(sslFactory); try { con.setRequestMethod(REQUEST_METHOD_GET); } catch (ProtocolException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } con.addRequestProperty(X_MS_VERSION_HEADER, X_MS_VERSION); InputStream responseStream = null; try { responseStream = (InputStream) con.getContent(); } catch (IOException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } return responseStream; }
protected void trustAllHosts() throws NoSuchAlgorithmException, KeyManagementException{ 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 { } } }; SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); }
private Boolean doInBackground2(String... params) { try { URL url = new URL(params[0]); URLConnection connection = url.openConnection(); if ("https".equals(url.getProtocol())) { if (sslSocketFactory == null) Log.w(TAG, "HTTPS requested but no sslSocketFactory provided"); else { HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) connection; Log.i(TAG, "Configuring the SSL factory: " + sslSocketFactory); httpsUrlConnection.setSSLSocketFactory(sslSocketFactory); httpsUrlConnection.setHostnameVerifier( new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } } Log.i(TAG, connection.toString()); connection.connect(); fileSize = connection.getContentLength(); Log.i(TAG, "fileSize=" + fileSize); File targetFile = new File(params[1]); File parentDir = targetFile.getParentFile(); if (!parentDir.exists()) { parentDir.mkdirs(); } if (!parentDir.exists() || !parentDir.isDirectory()) { Log.e(TAG, "Could not create the directory: \"" + parentDir + "\""); return false; } InputStream input = new BufferedInputStream(url.openStream()); OutputStream output = new FileOutputStream(targetFile); byte data[] = new byte[10 * 1024]; long transferred = 0; long count; while ((count = input.read(data)) != -1) { transferred += count; publishProgress(transferred, fileSize); output.write(data, 0, (int) count); } output.flush(); output.close(); input.close(); } catch (Exception e) { Log.e(TAG, "Got exception: ", e); return false; } return true; }