List of usage examples for javax.net.ssl HttpsURLConnection disconnect
public abstract void disconnect();
From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java
public static HttpsResponse putWithBasicAuth(String uri, String requestQuery, String contentType, String userName, String password) throws IOException { if (uri.startsWith("https://")) { URL url = new URL(uri); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("POST"); String encode = new String( new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes())) .replaceAll("\n", ""); ;// w w w . j a v a 2 s . c o m conn.setRequestProperty("Authorization", "Basic " + encode); conn.setDoOutput(true); // Triggers POST. conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty("Content-Length", "" + Integer.toString(requestQuery.getBytes().length)); conn.setUseCaches(false); conn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(requestQuery); conn.setReadTimeout(10000); conn.connect(); // Get the response StringBuilder sb = new StringBuilder(); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } } catch (FileNotFoundException ignored) { } finally { if (rd != null) { rd.close(); } wr.flush(); wr.close(); conn.disconnect(); } return new HttpsResponse(sb.toString(), conn.getResponseCode()); } return null; }
From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java
private String getPEMCertificateFromServer(String host) { HttpsURLConnection connection = null; try {/*from w w w . j a va2 s. c o m*/ URL url = new URL(host); connection = (HttpsURLConnection) url.openConnection(); connection.setHostnameVerifier(hostnameVerifier); connection.setSSLSocketFactory(generateSSLContextWhichAcceptAllSSLCertificats()); connection.connect(); java.security.cert.Certificate[] cert = connection.getServerCertificates(); connection.disconnect(); byte[] by = ((X509Certificate) cert[0]).getEncoded(); if (by.length != 0) { return BEGIN_CERT + Base64.getEncoder().encodeToString(by) + END_CERT; } } catch (MalformedURLException e) { if (!informConnectionManager(ConnectionManager.MALFORMED_URL_EXCEPTION)) { logger.error("A MalformedURLException occurred: ", e); } } catch (IOException e) { short code = ConnectionManager.GENERAL_EXCEPTION; if (e instanceof java.net.ConnectException) { code = ConnectionManager.CONNECTION_EXCEPTION; } else if (e instanceof java.net.UnknownHostException) { code = ConnectionManager.UNKNOWN_HOST_EXCEPTION; } if (!informConnectionManager(code) || code == -1) { logger.error("An IOException occurred: ", e); } } catch (CertificateEncodingException e) { logger.error("A CertificateEncodingException occurred: ", e); } finally { if (connection != null) { connection.disconnect(); } } return null; }
From source file:com.github.dfa.diaspora_android.task.GetPodsService.java
private void getPods() { /*/*ww w.j a v a2 s .c o m*/ * Most of the code in this AsyncTask is from the file getPodlistTask.java * from the app "Diaspora Webclient". * A few modifications and adaptations were made by me. * Source: * https://github.com/voidcode/Diaspora-Webclient/blob/master/src/com/voidcode/diasporawebclient/getPodlistTask.java * Thanks to Terkel Srensen ; License : GPLv3 */ AsyncTask<Void, Void, String[]> getPodsAsync = new AsyncTask<Void, Void, String[]>() { @Override protected String[] doInBackground(Void... params) { // TODO: Update deprecated code StringBuilder builder = new StringBuilder(); //HttpClient client = new DefaultHttpClient(); List<String> list = null; HttpsURLConnection connection; InputStream inStream; try { connection = NetCipher .getHttpsURLConnection("https://podupti.me/api.php?key=4r45tg&format=json"); int statusCode = connection.getResponseCode(); if (statusCode == 200) { inStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inStream)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } try { inStream.close(); } catch (IOException e) { /*Nothing to do*/} connection.disconnect(); } else { AppLog.e(this, "Failed to download list of pods"); } } catch (IOException e) { //TODO handle json buggy feed e.printStackTrace(); } //Parse the JSON Data try { JSONObject jsonObjectAll = new JSONObject(builder.toString()); JSONArray jsonArrayAll = jsonObjectAll.getJSONArray("pods"); AppLog.d(this, "Number of entries " + jsonArrayAll.length()); list = new ArrayList<>(); for (int i = 0; i < jsonArrayAll.length(); i++) { JSONObject jo = jsonArrayAll.getJSONObject(i); if (jo.getString("secure").equals("true")) list.add(jo.getString("domain")); } } catch (Exception e) { //TODO Handle Parsing errors here e.printStackTrace(); } if (list != null) return list.toArray(new String[list.size()]); else return null; } @Override protected void onPostExecute(String[] pods) { Intent broadcastIntent = new Intent(MESSAGE_PODS_RECEIVED); broadcastIntent.putExtra("pods", pods != null ? pods : new String[0]); LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(broadcastIntent); stopSelf(); } }; getPodsAsync.execute(); }
From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java
@Override public int checkConnection(String testRequest) { try {//from ww w .j ava2 s . co m HttpsURLConnection connection = getConnection(testRequest, connectTimeout, readTimeout); if (connection != null) { connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { if (IOUtils.toString(connection.getInputStream()).contains("Authentication failed")) { return ConnectionManager.AUTHENTIFICATION_PROBLEM; } } connection.disconnect(); return connection.getResponseCode(); } else { return ConnectionManager.GENERAL_EXCEPTION; } } catch (SocketTimeoutException e) { return ConnectionManager.SOCKET_TIMEOUT_EXCEPTION; } catch (java.net.ConnectException e) { return ConnectionManager.CONNECTION_EXCEPTION; } catch (MalformedURLException e) { return ConnectionManager.MALFORMED_URL_EXCEPTION; } catch (java.net.UnknownHostException e) { return ConnectionManager.UNKNOWN_HOST_EXCEPTION; } catch (IOException e) { return ConnectionManager.GENERAL_EXCEPTION; } }
From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java
public static HttpsResponse postWithBasicAuth(String uri, String requestQuery, String contentType, String userName, String password) throws IOException { if (uri.startsWith("https://")) { URL url = new URL(uri); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("POST"); String encode = new String( new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes())) .replaceAll("\n", ""); conn.setRequestProperty("Authorization", "Basic " + encode); conn.setDoOutput(true); // Triggers POST. conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty("Content-Length", "" + Integer.toString(requestQuery.getBytes().length)); conn.setUseCaches(false);// w ww. j a v a 2 s . co m conn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(requestQuery); conn.setReadTimeout(10000); conn.connect(); System.out.println(conn.getRequestMethod()); // Get the response StringBuilder sb = new StringBuilder(); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } } catch (FileNotFoundException ignored) { } finally { if (rd != null) { rd.close(); } wr.flush(); wr.close(); conn.disconnect(); } return new HttpsResponse(sb.toString(), conn.getResponseCode()); } return null; }
From source file:com.webarch.common.net.http.HttpService.java
/** * ?Https/* ww w . j a v a 2 s.c o m*/ * * @param requestUrl ? * @param requestMethod ? * @param trustManagers ?? * @param outputJson ? * @return */ public static String doHttpsRequest(String requestUrl, String requestMethod, TrustManager[] trustManagers, String outputJson) { String result = null; try { StringBuffer buffer = new StringBuffer(); // SSLContext?? SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, trustManagers, new java.security.SecureRandom()); // SSLContextSSLSocketFactory 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.setUseCaches(false); httpUrlConn.setRequestProperty("Accept-Charset", DEFAULT_CHARSET); httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=" + DEFAULT_CHARSET); // ?GET/POST httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect(); // ???? if (null != outputJson) { OutputStream outputStream = httpUrlConn.getOutputStream(); //?? outputStream.write(outputJson.getBytes(DEFAULT_CHARSET)); outputStream.close(); } // ??? InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, DEFAULT_CHARSET); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } result = buffer.toString(); bufferedReader.close(); inputStreamReader.close(); // ? inputStream.close(); httpUrlConn.disconnect(); } catch (ConnectException ce) { logger.error("Weixin server connection timed out.", ce); } catch (Exception e) { logger.error("https request error:", e); } finally { return result; } }
From source file:com.dsna.android.main.MainActivity.java
private void getPublicKeysFromServer() throws InvalidCertificateException, IOException, KeyManagementException, NoSuchAlgorithmException { KeyStore dsnaKeyStore = loadLocalTrustKeystore(); HttpsURLConnection urlConnection = NetworkUtil.establishHttpsConnection(publicKeyURL, dsnaKeyStore); String encodedPublicKeys = FileUtil.readString(urlConnection.getInputStream()); urlConnection.disconnect(); publicKeys = ASN1Util.extractPublicKey(ASN1Util.decodeIBESysPublicParams(encodedPublicKeys)); }
From source file:com.dsna.android.main.MainActivity.java
private void getSecretKeysFromServer() throws InvalidCertificateException, IOException, UnsupportedFormatException, KeyManagementException, NoSuchAlgorithmException { // Load publickey from file String mySecretKeyUrl = secretKeyURL + "?" + idParams + "=" + mUsername; KeyStore dsnaKeyStore = loadLocalTrustKeystore(); HttpsURLConnection urlConnection = NetworkUtil.establishHttpsConnection(mySecretKeyUrl, dsnaKeyStore); String encodedPrivateKeys = FileUtil.readString(urlConnection.getInputStream()); urlConnection.disconnect(); secretKeys = ASN1Util.extractClientSecretKey(ASN1Util.decodeIBEClientSecretParams(encodedPrivateKeys), getPublicKeys());/* w w w. j a va2 s. c o m*/ }
From source file:com.longtime.ajy.support.weixin.HttpsKit.java
/** * ??Get//w ww . j a v a 2 s . co m * * @param url * @return * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws IOException * @throws KeyManagementException */ public static String get(String url) {//throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException { InputStream in = null; HttpsURLConnection http = null; try { StringBuffer bufferRes = null; TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // SSLContextSSLSocketFactory SSLSocketFactory ssf = sslContext.getSocketFactory(); URL urlGet = new URL(url); http = (HttpsURLConnection) urlGet.openConnection(); // http.setConnectTimeout(TIME_OUT_CONNECT); // ? --?? http.setReadTimeout(TIME_OUT_READ); http.setRequestMethod("GET"); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); http.setSSLSocketFactory(ssf); http.setDoOutput(true); http.setDoInput(true); http.connect(); in = http.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET)); String valueString = null; bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null) { bufferRes.append(valueString); } return bufferRes.toString(); } catch (Exception e) { logger.error(String.format("HTTP GET url=[%s] due to fail.", url), e); } finally { if (null != in) { try { in.close(); } catch (IOException e) { logger.error(String.format("HTTP GET url=[%s] close inputstream due to fail.", url), e); } } if (http != null) { // http.disconnect(); } } return StringUtils.EMPTY; }
From source file:com.omertron.pushoverapi.PushoverApi.java
/** * Sends a raw bit of text via POST to PushoverApi. * * @param message/*www . j a va 2 s.c om*/ * @return JSON reply from PushoverApi. * @throws IOException */ private String sendToPushover(String message) throws IOException { URL pushoverUrl = new URL(PUSHOVER_URL); if (isDebug) System.out.println("Pushing with URL: " + message); HttpsURLConnection connection = (HttpsURLConnection) pushoverUrl.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); OutputStream outputStream = null; try { outputStream = connection.getOutputStream(); outputStream.write(message.getBytes(Charset.forName("UTF-8"))); } finally { if (outputStream != null) { outputStream.close(); } } InputStreamReader isr = null; BufferedReader br = null; StringBuilder output = new StringBuilder(); try { isr = new InputStreamReader(connection.getInputStream()); br = new BufferedReader(isr); connection.disconnect(); String outputCache; while ((outputCache = br.readLine()) != null) { output.append(outputCache); } } finally { if (isr != null) { isr.close(); } if (br != null) { br.close(); } } return output.toString(); }