Example usage for javax.net.ssl HttpsURLConnection disconnect

List of usage examples for javax.net.ssl HttpsURLConnection disconnect

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection disconnect.

Prototype

public abstract void disconnect();

Source Link

Document

Indicates that other requests to the server are unlikely in the near future.

Usage

From source file:it.jnrpe.plugin.CheckHttp.java

private void checkCertificateExpiryDate(URL url, List<Metric> metrics) throws Exception {
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
    SSLContext.setDefault(ctx);// w w  w. jav  a 2  s  .c o  m
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setHostnameVerifier(new HostnameVerifier() {
        public boolean verify(final String arg0, final SSLSession arg1) {
            return true;
        }
    });
    List<Date> expiryDates = new ArrayList<Date>();
    conn.getResponseCode();
    Certificate[] certs = conn.getServerCertificates();
    for (Certificate cert : certs) {
        X509Certificate x509 = (X509Certificate) cert;
        Date expiry = x509.getNotAfter();
        expiryDates.add(expiry);
    }

    conn.disconnect();
    Date today = new Date();
    for (Date date : expiryDates) {
        int diffInDays = (int) ((date.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
        metrics.add(new Metric("certificate", "", new BigDecimal(diffInDays), null, null));
    }
}

From source file:de.bps.webservices.clients.onyxreporter.OnyxReporterConnector.java

private boolean isServiceAvailable(String target) {

    HostnameVerifier hv = new HostnameVerifier() {
        @Override//from w  w w.  j  ava2 s .  c o  m
        public boolean verify(String urlHostName, SSLSession session) {
            if (urlHostName.equals(session.getPeerHost())) {
                return true;
            } else {
                return false;
            }
        }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(hv);

    try {
        URL url = new URL(target + "?wsdl");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        if (con instanceof HttpsURLConnection) {
            HttpsURLConnection sslconn = (HttpsURLConnection) con;
            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 (Exception e) {
        Tracing.createLoggerFor(getClass()).error("Error while trying to connect to webservice: " + target, e);
    }
    return false;
}

From source file:org.openmrs.module.rheashradapter.util.GenerateORU_R01Alert.java

public String callQueryFacility(String msg, Encounter e)
        throws IOException, TransformerFactoryConfigurationError, TransformerException {

    Cohort singlePatientCohort = new Cohort();
    singlePatientCohort.addMember(e.getPatient().getId());

    Map<Integer, String> patientIdentifierMap = Context.getPatientSetService()
            .getPatientIdentifierStringsByType(singlePatientCohort, Context.getPatientService()
                    .getPatientIdentifierTypeByName(RHEAHL7Constants.IDENTIFIER_TYPE));

    // Setup connection
    String id = patientIdentifierMap.get(patientIdentifierMap.keySet().iterator().next());
    URL url = new URL(hostname + "/ws/rest/v1/alerts");
    System.out.println("full url " + url);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);/*  ww  w.  j a v  a  2s.c  om*/
    conn.setRequestMethod("POST");
    conn.setDoInput(true);

    // This is important to get the connection to use our trusted
    // certificate
    conn.setSSLSocketFactory(sslFactory);

    addHTTPBasicAuthProperty(conn);
    // conn.setConnectTimeout(timeOut);
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    log.error("body" + msg);
    out.write(msg);
    out.close();
    conn.connect();
    String headerValue = conn.getHeaderField("http.status");

    // Test response code
    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }

    String result = convertInputStreamToString(conn.getInputStream());
    conn.disconnect();

    return result;
}

From source file:org.whispersystems.textsecure.push.PushServiceSocket.java

private void uploadExternalFile(String method, String url, byte[] data) throws IOException {
    URL uploadUrl = new URL(url);
    HttpsURLConnection connection = (HttpsURLConnection) uploadUrl.openConnection();
    connection.setDoOutput(true);/*from  w  w w .  ja v  a  2 s . co  m*/
    connection.setRequestMethod(method);
    connection.setRequestProperty("Content-Type", "application/octet-stream");
    connection.connect();

    try {
        OutputStream out = connection.getOutputStream();
        out.write(data);
        out.close();

        if (connection.getResponseCode() != 200) {
            throw new IOException(
                    "Bad response: " + connection.getResponseCode() + " " + connection.getResponseMessage());
        }
    } finally {
        connection.disconnect();
    }
}

From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java

public static HttpsResponse postWithBasicAuth(String uri, String requestQuery, 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 ww .  java 2  s.c  o m*/
        conn.setRequestProperty("Authorization", "Basic " + encode);
        conn.setDoOutput(true); // Triggers POST.
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        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();
        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);
            }
            return new HttpsResponse(sb.toString(), conn.getResponseCode());
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            wr.flush();
            wr.close();
            conn.disconnect();
        }
    }
    return null;
}

From source file:org.openmrs.module.rheapocadapter.handler.ConnectionHandler.java

public String[] callGet(String stringUrl) {
    try {//from  ww  w  .  j  a  v a  2 s . c  o  m

        // Setup connection
        URL url = new URL(stringUrl);

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        // This is important to get the connection to use our trusted
        // certificate
        conn.setSSLSocketFactory(sslFactory);

        addHTTPBasicAuthProperty(conn);
        //conn.setConnectTimeout(timeOut);
        // bug fixing for SSL error, this is a temporary fix, need to find a
        // long term one
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        // printHttpsCert(conn);
        conn.connect();
        int code = conn.getResponseCode();

        if (code >= 200 && code < 300) {
            String result = IOUtils.toString(conn.getInputStream());
            conn.disconnect();
            return new String[] { code + "", result };
        } else {
            conn.disconnect();
            return new String[] { code + "", "Server returned " + code + " response code" };
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
        log.error("MalformedURLException while callGet " + e.getMessage());
        return new String[] { 400 + "", e.getMessage() };
    } catch (IOException e) {
        e.printStackTrace();
        log.error("IOException while callGet " + e.getMessage());
        return new String[] { 600 + "", e.getMessage() };
    }
}

From source file:org.kuali.mobility.push.service.send.AndroidSendService.java

/**
 * Attempts to send a push notification to the specified registration IDs.
 * If the connection limit is currently reached, the call to this method will cause the 
 * current thread to block until a connection is available.
 * @param push// www  . ja v a 2  s  .  co m
 * @param registrationIds
 */
private void executePush(Push push, List<String> registrationIds) {
    HttpsURLConnection conn = null;
    try {
        this.androidConnectionLimit.acquire(); // Attempt to acquire a lock for a connection
        conn = createConnection();
        JSONObject request = buildJsonMessage(push, registrationIds);
        String responseData = sendToGCM(conn, request.toString());
        JSONObject response = JSONObject.fromObject(responseData);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Response from GCM : " + responseData);
        }
        handleResponse(request, response);
    } catch (Exception e) {
        LOG.error("Exception while trying to send notification", e);
    } finally {
        this.androidConnectionLimit.release();
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:org.liberty.android.fantastischmemo.downloader.quizlet.lib.java

private static String makePostApiCall(URL url, String content, String authToken) throws IOException {
    HttpsURLConnection conn = null;
    OutputStreamWriter writer = null;
    String res = "";
    try {//from  w ww  .j a  v a  2  s .c  om
        conn = (HttpsURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.addRequestProperty("Authorization", "Bearer " + authToken);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(content);
        writer.close();

        if (conn.getResponseCode() / 100 >= 3) {
            Log.v("makePostApiCall", "Post content is: " + content);
            String error = "";
            try {
                JsonReader r = new JsonReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
                r.beginObject();
                while (r.hasNext()) {
                    error += r.nextName() + ": " + r.nextString() + "\r\n";
                }
                r.endObject();
                r.close();
            } catch (Throwable eex) {

            }
            Log.v("makePostApiCall", "Error string is: " + error);
            res = error;
            throw new IOException(
                    "Response code: " + conn.getResponseCode() + " URL is: " + url + " \nError: " + error);
        } else {
            JsonReader r = new JsonReader(new InputStreamReader(conn.getInputStream()));
            r.beginObject();
            while (r.hasNext()) {
                try {
                    res += r.nextName() + ": " + r.nextString() + "\n";
                } catch (Exception ex) {
                    r.skipValue();
                }
            }
            return res;
        }
    } finally {
        conn.disconnect();
        //return res;
    }
}

From source file:org.apache.hadoop.hdfsproxy.ProxyUtil.java

static boolean sendCommand(Configuration conf, String path) throws IOException {
    setupSslProps(conf);//from  www.  java 2  s . c  o m
    int sslPort = getSslAddr(conf).getPort();
    int err = 0;
    StringBuilder b = new StringBuilder();

    HostsFileReader hostsReader = new HostsFileReader(conf.get("hdfsproxy.hosts", "hdfsproxy-hosts"), "");
    Set<String> hostsList = hostsReader.getHosts();
    for (String hostname : hostsList) {
        HttpsURLConnection connection = null;
        try {
            connection = openConnection(hostname, sslPort, path);
            connection.connect();
            if (LOG.isDebugEnabled()) {
                StringBuffer sb = new StringBuffer();
                X509Certificate[] clientCerts = (X509Certificate[]) connection.getLocalCertificates();
                if (clientCerts != null) {
                    for (X509Certificate cert : clientCerts)
                        sb.append("\n Client certificate Subject Name is "
                                + cert.getSubjectX500Principal().getName());
                } else {
                    sb.append("\n No client certificates were found");
                }
                X509Certificate[] serverCerts = (X509Certificate[]) connection.getServerCertificates();
                if (serverCerts != null) {
                    for (X509Certificate cert : serverCerts)
                        sb.append("\n Server certificate Subject Name is "
                                + cert.getSubjectX500Principal().getName());
                } else {
                    sb.append("\n No server certificates were found");
                }
                LOG.debug(sb.toString());
            }
            if (connection.getResponseCode() != HttpServletResponse.SC_OK) {
                b.append("\n\t" + hostname + ": " + connection.getResponseCode() + " "
                        + connection.getResponseMessage());
                err++;
            }
        } catch (IOException e) {
            b.append("\n\t" + hostname + ": " + e.getLocalizedMessage());
            if (LOG.isDebugEnabled())
                LOG.debug("Exception happend for host " + hostname, e);
            err++;
        } finally {
            if (connection != null)
                connection.disconnect();
        }
    }
    if (err > 0) {
        System.err.print("Command failed on the following " + err + " host" + (err == 1 ? ":" : "s:")
                + b.toString() + "\n");
        return false;
    }
    return true;
}

From source file:learn.encryption.ssl.SSLContext_Https.java

/**
 * Post??web??,?utf-8//ww w  .j av a  2s  .c  o  m
 * 
 * ?UTF8
 * 
 * @param actionUrl
 * @param params
 * @param timeout   
 * @return
 * @throws InvalidParameterException
 * @throws NetWorkException
 * @throws IOException
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 * @throws Exception
 */
public static String post(String url, Map<String, String> params, int timeout)
        throws IOException, IllegalArgumentException, IllegalAccessException {
    if (url == null || url.equals(""))
        throw new IllegalArgumentException("url ");
    if (params == null)
        throw new IllegalArgumentException("params ?");
    if (url.indexOf('?') > 0) {
        url = url
                + "&token=A04BCQULBDgEFB1BQk5cU1NRU19cQU1WWkBPCg0FAwIkCVpZWl1UVExTXFRDSFZSSVlPSkADGhw7HAoQEQMDRFhAWUJYV0hBVE4JAxQLCQlPQ1oiNig/KSsmSEBPGBsAFxkDEkBYSF1eTk1USVldU1FQSEBPFh0OMQhPXEBQSBE=";
    } else {
        url = url
                + "?token=A04BCQULBDgEFB1BQk5cU1NRU19cQU1WWkBPCg0FAwIkCVpZWl1UVExTXFRDSFZSSVlPSkADGhw7HAoQEQMDRFhAWUJYV0hBVE4JAxQLCQlPQ1oiNig/KSsmSEBPGBsAFxkDEkBYSF1eTk1USVldU1FQSEBPFh0OMQhPXEBQSBE=";
    }

    String sb2 = "";
    String BOUNDARY = java.util.UUID.randomUUID().toString();
    String PREFIX = "--", LINEND = "\r\n";
    String MULTIPART_FROM_DATA = "multipart/form-data";
    String CHARSET = "UTF-8";
    // try {
    URL uri = new URL(url);
    HttpsURLConnection conn = (HttpsURLConnection) uri.openConnection();
    // 
    conn.setConnectTimeout(timeout);
    conn.setReadTimeout(timeout);
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("connection", "keep-alive");
    conn.setRequestProperty("Charsert", "UTF-8");
    conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    conn.setSSLSocketFactory(ssf);
    conn.setHostnameVerifier(HOSTNAME_VERIFIER);

    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        sb.append(PREFIX);
        sb.append(BOUNDARY);
        sb.append(LINEND);
        sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
        sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
        sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
        sb.append(LINEND);
        sb.append(entry.getValue());
        sb.append(LINEND);
    }

    DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
    outStream.write(sb.toString().getBytes("UTF-8"));
    InputStream in = null;

    byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
    outStream.write(end_data);
    outStream.flush();

    int res = conn.getResponseCode();
    if (res == 200) {
        in = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        String line = "";
        for (line = br.readLine(); line != null; line = br.readLine()) {
            sb2 = sb2 + line;
        }
    }
    outStream.close();
    conn.disconnect();
    return sb2;
}