Java Code Examples for javax.net.ssl.HttpsURLConnection#disconnect()
The following examples show how to use
javax.net.ssl.HttpsURLConnection#disconnect() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpsCreateSockTest.java From jdk8u60 with GNU General Public License v2.0 | 8 votes |
void doClient() throws IOException { InetSocketAddress address = httpsServer.getAddress(); URL url = new URL("https://localhost:" + address.getPort() + "/"); System.out.println("trying to connect to " + url + "..."); HttpsURLConnection uc = (HttpsURLConnection) url.openConnection(); uc.setHostnameVerifier(new AllHostnameVerifier()); if (uc instanceof javax.net.ssl.HttpsURLConnection) { ((javax.net.ssl.HttpsURLConnection) uc).setSSLSocketFactory(new SimpleSSLSocketFactory()); System.out.println("Using TestSocketFactory"); } uc.connect(); System.out.println("CONNECTED " + uc); System.out.println(uc.getResponseMessage()); uc.disconnect(); }
Example 2
Source File: HttpsCreateSockTest.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 6 votes |
void doClient() throws IOException { InetSocketAddress address = httpsServer.getAddress(); URL url = new URL("https://localhost:" + address.getPort() + "/"); System.out.println("trying to connect to " + url + "..."); HttpsURLConnection uc = (HttpsURLConnection) url.openConnection(); uc.setHostnameVerifier(new AllHostnameVerifier()); if (uc instanceof javax.net.ssl.HttpsURLConnection) { ((javax.net.ssl.HttpsURLConnection) uc).setSSLSocketFactory(new SimpleSSLSocketFactory()); System.out.println("Using TestSocketFactory"); } uc.connect(); System.out.println("CONNECTED " + uc); System.out.println(uc.getResponseMessage()); uc.disconnect(); }
Example 3
Source File: HttpsCreateSockTest.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
void doClient() throws IOException { InetSocketAddress address = httpsServer.getAddress(); URL url = new URL("https://localhost:" + address.getPort() + "/"); System.out.println("trying to connect to " + url + "..."); HttpsURLConnection uc = (HttpsURLConnection) url.openConnection(); uc.setHostnameVerifier(new AllHostnameVerifier()); if (uc instanceof javax.net.ssl.HttpsURLConnection) { ((javax.net.ssl.HttpsURLConnection) uc).setSSLSocketFactory(new SimpleSSLSocketFactory()); System.out.println("Using TestSocketFactory"); } uc.connect(); System.out.println("CONNECTED " + uc); System.out.println(uc.getResponseMessage()); uc.disconnect(); }
Example 4
Source File: HttpsCreateSockTest.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
void doClient() throws IOException { InetSocketAddress address = httpsServer.getAddress(); URL url = new URL("https://localhost:" + address.getPort() + "/"); System.out.println("trying to connect to " + url + "..."); HttpsURLConnection uc = (HttpsURLConnection) url.openConnection(); uc.setHostnameVerifier(new AllHostnameVerifier()); if (uc instanceof javax.net.ssl.HttpsURLConnection) { ((javax.net.ssl.HttpsURLConnection) uc).setSSLSocketFactory(new SimpleSSLSocketFactory()); System.out.println("Using TestSocketFactory"); } uc.connect(); System.out.println("CONNECTED " + uc); System.out.println(uc.getResponseMessage()); uc.disconnect(); }
Example 5
Source File: ExprUrlSSLVerifier.java From skUtilities with GNU General Public License v3.0 | 6 votes |
@Override @Nullable protected String[] get(Event e) { try { HttpsURLConnection c = (HttpsURLConnection) new URL(url.getSingle(e)).openConnection(); c.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11"); c.connect(); for (Certificate cert : c.getServerCertificates()) { if (cert instanceof X509Certificate) { c.disconnect(); X509Certificate sc = (X509Certificate) cert; String[] s = sc.getIssuerX500Principal().getName().split("O="); s = s[1].split(",C"); return new String[]{s[0]}; } } } catch (Exception x) { skUtilities.prSysE("Error Reading from: '" + url.getSingle(e) + "' Is the site down?", getClass().getSimpleName(), x); } return null; }
Example 6
Source File: ConversationFragment.java From weMessage with GNU Affero General Public License v3.0 | 6 votes |
private String parseURL(String urlString){ if (!urlString.toLowerCase().startsWith("http://") && !urlString.toLowerCase().startsWith("https://")){ String https = "https://" + urlString; try { URL url = new URL(urlString); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); InputStream inputStream = urlConnection.getInputStream(); inputStream.close(); urlConnection.disconnect(); return https; }catch (Exception ex){ return "http://" + urlString; } }else { return urlString; } }
Example 7
Source File: ExprUrlSSLSerialNumber.java From skUtilities with GNU General Public License v3.0 | 6 votes |
@Override @Nullable protected String[] get(Event e) { try { HttpsURLConnection c = (HttpsURLConnection) new URL(url.getSingle(e)).openConnection(); c.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11"); c.connect(); for (Certificate cert : c.getServerCertificates()) { if (cert instanceof X509Certificate) { c.disconnect(); X509Certificate sc = (X509Certificate) cert; return new String[]{sc.getSerialNumber().toString(16)}; } } } catch (Exception x) { skUtilities.prSysE("Error Reading from: '" + url.getSingle(e) + "' Is the site down?", getClass().getSimpleName(), x); } return null; }
Example 8
Source File: HttpsCreateSockTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
void doClient() throws IOException { InetSocketAddress address = httpsServer.getAddress(); URL url = new URL("https://localhost:" + address.getPort() + "/"); System.out.println("trying to connect to " + url + "..."); HttpsURLConnection uc = (HttpsURLConnection) url.openConnection(); uc.setHostnameVerifier(new AllHostnameVerifier()); if (uc instanceof javax.net.ssl.HttpsURLConnection) { ((javax.net.ssl.HttpsURLConnection) uc).setSSLSocketFactory(new SimpleSSLSocketFactory()); System.out.println("Using TestSocketFactory"); } uc.connect(); System.out.println("CONNECTED " + uc); System.out.println(uc.getResponseMessage()); uc.disconnect(); }
Example 9
Source File: GoogleUriActivity.java From LocationPrivacy with GNU General Public License v3.0 | 6 votes |
@Override protected String doInBackground(Void... params) { String result = null; HttpsURLConnection connection = null; try { connection = NetCipher.getHttpsURLConnection(urlString); connection.setRequestMethod("HEAD"); connection.setInstanceFollowRedirects(false); // gzip encoding seems to cause problems // https://code.google.com/p/android/issues/detail?id=24672 connection.setRequestProperty("Accept-Encoding", ""); connection.connect(); connection.getResponseCode(); // this actually makes it go result = connection.getHeaderField("Location"); } catch (IOException e) { e.printStackTrace(); } finally { if (connection != null) connection.disconnect(); } return result; }
Example 10
Source File: UpdateNotifier.java From SuperVanish with Mozilla Public License 2.0 | 6 votes |
private String fetchLatestVersion() { try { HttpsURLConnection con = (HttpsURLConnection) new URL( "https://api.spigotmc.org/legacy/update.php?resource=1331").openConnection(); con.setConnectTimeout(20 * 1000); con.setReadTimeout(20 * 1000); String version; try (BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()))) { version = reader.readLine(); } con.disconnect(); if (version.length() <= 7) return version; else throw new RuntimeException("'" + version + "' is not a valid version"); } catch (Exception e) { plugin.log(Level.WARNING, "Failed to check for an update: " + e.getMessage()); return "Error"; } }
Example 11
Source File: Utils.java From NationStatesPlusPlus with MIT License | 5 votes |
private static String executeUploadToImgur(String url, String base64, String clientKey) throws IOException { HttpsURLConnection conn = (HttpsURLConnection) (new URL("https://api.imgur.com/3/image")).openConnection(); conn.addRequestProperty("Authorization", "Client-ID " + clientKey); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); try (OutputStream out = conn.getOutputStream()) { if (url != null) { IOUtils.write("image=" + EncodingUtil.encodeURIComponent(url) + "&type=URL", out); } else { IOUtils.write("image=" + EncodingUtil.encodeURIComponent(base64) + "&type=base64", out); } out.flush(); } try (InputStream stream = conn.getInputStream()) { Map<String, Object> result = new ObjectMapper().readValue(stream, new TypeReference<HashMap<String,Object>>() {}); if (result != null && result.containsKey("data")) { @SuppressWarnings("unchecked") Map<String, Object> data = (Map<String, Object>) result.get("data"); if (data != null && data.containsKey("link")) { String link = (String) data.get("link"); return "https://" + link.substring(7); } } } finally { conn.disconnect(); } return null; }
Example 12
Source File: ClientAuthTest.java From cxf with Apache License 2.0 | 5 votes |
@org.junit.Test public void testSSLConnectionUsingJavaAPIs() throws Exception { URL service = new URL("https://localhost:" + PORT); HttpsURLConnection connection = (HttpsURLConnection) service.openConnection(); connection.setHostnameVerifier(new DisableCNCheckVerifier()); SSLContext sslContext = SSLContext.getInstance("TLS"); KeyStore ts = KeyStore.getInstance("JKS"); try (InputStream trustStore = ClassLoaderUtils.getResourceAsStream("keys/Truststore.jks", ClientAuthTest.class)) { ts.load(trustStore, "password".toCharArray()); } TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ts); KeyStore ks = KeyStore.getInstance("JKS"); try (InputStream keyStore = ClassLoaderUtils.getResourceAsStream("keys/Morpit.jks", ClientAuthTest.class)) { ks.load(keyStore, "password".toCharArray()); } KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, "password".toCharArray()); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new java.security.SecureRandom()); connection.setSSLSocketFactory(sslContext.getSocketFactory()); connection.connect(); connection.disconnect(); }
Example 13
Source File: RestClient.java From constellation with Apache License 2.0 | 5 votes |
/** * Post method similar to {@code post} but has the option to supply a json * string that will be posted in the message body. * * @param url The URL to request * @param params A simple key/value pair in which values do not contain * Arrays, Sets etc * @param json The json string to be posted in the message body * * @throws IOException */ public void postWithJson(final String url, final Map<String, String> params, final String json) throws IOException { beforePost(url, params); HttpsURLConnection connection = null; try { connection = makePostConnection(url, params); try (final BufferedWriter request = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8.name()))) { request.write(json); request.flush(); } responseCode = connection.getResponseCode(); responseMessage = connection.getResponseMessage(); headerFields = connection.getHeaderFields(); bytes = null; if (Response.isCodeSuccess(responseCode)) { bytes = getBody(connection, responseCode); } } catch (IOException ex) { Exceptions.printStackTrace(ex); } finally { if (connection != null) { connection.disconnect(); } } afterPost(url, params); }
Example 14
Source File: TestPhases.java From testgrid with Apache License 2.0 | 5 votes |
private void testSummaryValidate(String testplan, String jobName) throws Exception { URL url = new URL(TestProperties.tgDashboardApiUrl + "/test-plans/test-summary/" + testplan); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setDoOutput(true); con.setRequestProperty("Authorization", testProperties.tgApiToken); SSLSocketFactory sslSocketFactory = createSslSocketFactory(); con.setSSLSocketFactory(sslSocketFactory); StringBuffer response; try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) { String inputLine; response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } } JSONObject responseObj = new JSONObject(response.toString()); responseObj = responseObj.getJSONArray("scenarioSummaries").getJSONObject(0); if (jobName.equals("Phase-1")) { Assert.assertEquals(responseObj.getInt("totalSuccess"), 541); } else { Assert.assertEquals(responseObj.getInt("totalSuccess"), 1); } Assert.assertEquals(responseObj.getInt("totalFail"), 0); if (jobName.equals("Phase-1")) { Assert.assertEquals(responseObj.getString("scenarioDescription"), "integration"); } else { Assert.assertEquals(responseObj.getString("scenarioDescription"), "1-integrating-systems-that-communicate" + "-in-heterogeneous-message-formats"); } con.disconnect(); }
Example 15
Source File: TestPhases.java From testgrid with Apache License 2.0 | 5 votes |
private JenkinsJob getLastJob(URL url, String authHeader) throws Exception { HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestProperty("Authorization", authHeader); con.setRequestMethod("GET"); con.setDoOutput(true); SSLSocketFactory sslSocketFactory = createSslSocketFactory(); con.setSSLSocketFactory(sslSocketFactory); StringBuffer response; try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) { String inputLine; response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } } JSONObject responseObj = new JSONObject(response.toString()); JenkinsJob jenkinsJob; if (responseObj.getBoolean("building")) { jenkinsJob = new JenkinsJob(responseObj.getString("url"), responseObj.getString("id"), responseObj.getBoolean("building")); } else { jenkinsJob = new JenkinsJob(responseObj.getString("url"), responseObj.getString("result"), responseObj.getString("id"), responseObj.getBoolean("building")); } con.disconnect(); return jenkinsJob; }
Example 16
Source File: OnyxReporterWebserviceClient.java From olat with Apache License 2.0 | 5 votes |
public boolean isServiceAvailable(final String target) { final HostnameVerifier hv = new HostnameVerifier() { @Override public boolean verify(final String urlHostName, final SSLSession session) { if (urlHostName.equals(session.getPeerHost())) { return true; } else { return false; } } }; HttpsURLConnection.setDefaultHostnameVerifier(hv); try { final URL url = new URL(target + "?wsdl"); final HttpURLConnection con = (HttpURLConnection) url.openConnection(); if (con instanceof HttpsURLConnection) { final HttpsURLConnection sslconn = (HttpsURLConnection) con; final SSLContext context = SSLContext.getInstance("SSL"); context.init(SSLConfigurationModule.getKeyManagers(), SSLConfigurationModule.getTrustManagers(), new java.security.SecureRandom()); sslconn.setSSLSocketFactory(context.getSocketFactory()); sslconn.connect(); if (sslconn.getResponseCode() == HttpURLConnection.HTTP_OK) { sslconn.disconnect(); return true; } } else { con.connect(); if (con.getResponseCode() == HttpURLConnection.HTTP_OK) { con.disconnect(); return true; } } } catch (final Exception e) { private static final Logger log = LoggerHelper.getLogger(); } return false; }
Example 17
Source File: CommonUtil.java From Shop-for-JavaWeb with MIT License | 4 votes |
/** * 发送https请求 * @param requestUrl 请求地址 * @param requestMethod 请求方式(GET、POST) * @param outputStr 提交的数据 * @return 返回微信服务器响应的信息 */ public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) { try { // 创建SSLContext对象,并使用我们指定的信任管理器初始化 TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // 从上述SSLContext对象中得到SSLSocketFactory对象 SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setSSLSocketFactory(ssf); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); // 设置请求方式(GET/POST) conn.setRequestMethod(requestMethod); conn.setRequestProperty("content-type", "application/x-www-form-urlencoded"); // 当outputStr不为null时向输出流写数据 if (null != outputStr) { OutputStream outputStream = conn.getOutputStream(); // 注意编码格式 outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); } // 从输入流读取返回内容 InputStream inputStream = conn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; StringBuffer buffer = new StringBuffer(); while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } // 释放资源 bufferedReader.close(); inputStreamReader.close(); inputStream.close(); inputStream = null; conn.disconnect(); return buffer.toString(); } catch (ConnectException ce) { log.error("连接超时:{}", ce); } catch (Exception e) { log.error("https请求异常:{}", e); } return null; }
Example 18
Source File: WxstoreUtils.java From jeewx-api with Apache License 2.0 | 4 votes |
public static JSONObject httpRequest2(String requestUrl, String requestMethod, byte[] outputStr) { JSONObject jsonObject = null; StringBuffer buffer = new StringBuffer(); try { TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new SecureRandom()); SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection) url .openConnection(); httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) { httpUrlConn.connect(); } if (null != outputStr) { OutputStream outputStream = httpUrlConn.getOutputStream(); outputStream.write(outputStr); outputStream.close(); } InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader( inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader( inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); inputStream.close(); inputStream = null; httpUrlConn.disconnect(); jsonObject = JSONObject.fromObject(buffer.toString()); } catch (ConnectException ce) { System.out.print("Weixin server connection timed out."); } catch (Exception e) { System.out.print("https request error:{}" + e.getMessage()); } return jsonObject; }
Example 19
Source File: MarkOrVerifyPin.java From WhereAreTheEyes with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Override protected Void doInBackground(MarkData... params) { Location l = params[0].loc; String username = params[0].username; Context context = params[0].context; Activity activity = params[0].activity; if( username.length() == 0 ) return null; if( l == null ) { Log.d("Marking", "Location was null!"); return null; // Location data isn't available yet! } try { List<AbstractMap.SimpleEntry> httpParams = new ArrayList<AbstractMap.SimpleEntry>(); httpParams.add(new AbstractMap.SimpleEntry<>("username", username)); httpParams.add(new AbstractMap.SimpleEntry<>("latitude", Double.valueOf(l.getLatitude()).toString())); httpParams.add(new AbstractMap.SimpleEntry<>("longitude", Double.valueOf(l.getLongitude()).toString())); // Vibrate once, let the user know we received the button tap Vibrate.pulse(context); URL url = new URL("https://" + Constants.DOMAIN + "/markPin"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); try { conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(getQuery(httpParams)); writer.flush(); writer.close(); os.close(); String response = ""; int responseCode = conn.getResponseCode(); if( responseCode == HttpsURLConnection.HTTP_OK ) { String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = br.readLine()) != null) { response += line; } } handleResponse(response, context, activity); Log.d("Marking", "Marked new pin, got response: " + response); } finally { conn.disconnect(); } } catch( Exception e ) { Log.e("MarkPin", "Error marking pin: " + e.getMessage()); Log.e("MarkPin", Log.getStackTraceString(e)); } return null; }
Example 20
Source File: UploadToWeb.java From open-ig with GNU Lesser General Public License v3.0 | 4 votes |
/** * Upload a file from the local directory into the specified project. * @param username the username * @param password the SVN password * @param project the project name * @param filename the file */ static void uploadFile(String username, String password, String project, String filename) { try { String boundary = "----------Googlecode_boundary_reindeer_flotilla"; URL u = new URL(String.format("https://%s.googlecode.com/files", project)); HttpsURLConnection c = (HttpsURLConnection)u.openConnection(); try { String up = Base64.encodeBytes(String.format("%s:%s", username, password).getBytes("UTF-8")); c.setRequestProperty("Authorization", "Basic " + up); c.setRequestProperty("Content-Type", String.format("multipart/form-data; boundary=%s", boundary)); c.setRequestProperty("User-Agent", "Open-IG Google Code Upload 0.1"); c.setRequestMethod("POST"); c.setDoInput(true); c.setDoOutput(true); c.setAllowUserInteraction(false); c.connect(); try (OutputStream out = c.getOutputStream()) { out.write(("--" + boundary + "\r\n").getBytes("ISO-8859-1")); out.write("Content-Disposition: form-data; name=\"summary\"\r\n\r\nUpload.\r\n".getBytes("ISO-8859-1")); out.write(("--" + boundary + "\r\n").getBytes("ISO-8859-1")); out.write(String.format("Content-Disposition: form-data; name=\"filename\"; filename=\"%s1\"\r\n", filename).getBytes("ISO-8859-1")); out.write("Content-Type: application/octet-stream\r\n".getBytes("ISO-8859-1")); out.write("\r\n".getBytes("ISO-8859-1")); out.write(IOUtils.load(filename)); out.write(("\r\n\r\n--" + boundary + "--\r\n").getBytes("ISO-8859-1")); out.flush(); } System.out.write(IOUtils.load(c.getInputStream())); System.out.println(c.getResponseCode() + ": " + c.getResponseMessage()); } finally { c.disconnect(); } } catch (IOException ex) { Exceptions.add(ex); } }