Example usage for javax.net.ssl HttpsURLConnection connect

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

Introduction

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

Prototype

public abstract void connect() throws IOException;

Source Link

Document

Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.

Usage

From source file:com.webarch.common.net.http.HttpService.java

/**
 * ?Https//from   ww w. j  a  v  a2  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.illusionaryone.GoogleURLShortenerAPIv1.java

@SuppressWarnings("UseSpecificCatch")
private static JSONObject readJsonFromUrl(String urlAddress, String longURL) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    URL urlRaw;/*ww  w.j  a v  a2 s  . c om*/
    HttpsURLConnection urlConn;
    String jsonRequest = "";
    String jsonText = "";

    try {
        jsonRequest = "{ 'longUrl': '" + longURL + "'}";
        byte[] postRequest = jsonRequest.getBytes("UTF-8");

        urlRaw = new URL(urlAddress);
        urlConn = (HttpsURLConnection) urlRaw.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setRequestMethod("POST");
        urlConn.addRequestProperty("Content-Type", "application/json");
        urlConn.addRequestProperty("Content-Length", String.valueOf(postRequest.length));
        urlConn.addRequestProperty("Accept", "application/vnd.github.v3+json");
        urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 "
                + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");
        urlConn.connect();
        urlConn.getOutputStream().write(postRequest);

        if (urlConn.getResponseCode() == 200) {
            inputStream = urlConn.getInputStream();
        } else {
            inputStream = urlConn.getErrorStream();
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
        jsonText = readAll(rd);
        jsonResult = new JSONObject(jsonText);
        fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText);
    } catch (JSONException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText);
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (UnsupportedEncodingException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "UnsupportedEncodingException", ex.getMessage(),
                jsonText);
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (NullPointerException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (MalformedURLException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (SocketTimeoutException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (IOException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (Exception ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } finally {
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (IOException ex) {
                fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
                com.gmt2001.Console.err
                        .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
            }
    }

    return (jsonResult);
}

From source file:ezbake.deployer.publishers.SecurityServiceClient.java

/**
 * The applicationId is part of the REST call to the Security Service.
 * Returns an empty list if no certificates were found or throws exception if
 * something went wrong with Security Service communication.
 *//*  w ww  . j a v  a2s. c  o  m*/
@Override
public List<ArtifactDataEntry> get(String applicationId, String securityId) throws DeploymentException {
    try {
        ArrayList<ArtifactDataEntry> certList = new ArrayList<ArtifactDataEntry>();
        String endpoint = config.getSecurityServiceBasePath() + "/registrations/" + securityId + "/download";
        URL url = new URL(endpoint);
        HttpsURLConnection urlConn = openUrlConnection(url);
        urlConn.connect();

        // Read in tar file of certificates into byte array
        BufferedInputStream in = new BufferedInputStream(urlConn.getInputStream());
        // Create CertDataEntry list from tarFile byte array
        TarArchiveInputStream tarIn = new TarArchiveInputStream(in);
        TarArchiveEntry entry = tarIn.getNextTarEntry();
        while (entry != null) {
            if (!entry.isDirectory()) {
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                IOUtils.copy(tarIn, bout);
                byte[] certData = bout.toByteArray();
                String certFileName = entry.getName().substring(entry.getName().lastIndexOf("/") + 1,
                        entry.getName().length());
                TarArchiveEntry tae = new TarArchiveEntry(
                        Files.get(SSL_CONFIG_DIRECTORY, securityId, certFileName));
                ArtifactDataEntry cde = new ArtifactDataEntry(tae, certData);
                certList.add(cde);
                bout.close();
            }

            entry = tarIn.getNextTarEntry();
        }
        tarIn.close();

        return certList;
    } catch (Exception e) {
        log.error("Unable to download certificates from security service.", e);
        throw new DeploymentException(
                "Unable to download certificates from security service. " + e.getMessage());
    }
}

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

public static HttpsResponse deleteWithBasicAuth(String uri, String contentType, String userName,
        String password) throws IOException {
    if (uri.startsWith("https://")) {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("DELETE");
        String encode = new String(
                new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes()))
                        .replaceAll("\n", "");
        ;/*www . j av  a 2s  . c  o  m*/
        conn.setRequestProperty("Authorization", "Basic " + encode);
        if (contentType != null) {
            conn.setRequestProperty("Content-Type", contentType);
        }
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        conn.connect();
        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();
            }
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:com.longtime.ajy.support.weixin.HttpsKit.java

/**
 * ??Get/*from w  w w  .  j a  va2 s.  c om*/
 * 
 * @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.longtime.ajy.support.weixin.HttpsKit.java

/**
 * ??Post//from  ww w  . ja v a  2 s .  c  om
 * 
 * @param url
 * @param params
 * @return
 * @throws IOException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static String post(String url, String params) {//throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {

    OutputStream out = null;
    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("POST");
        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        http.setSSLSocketFactory(ssf);
        http.setDoOutput(true);
        http.setDoInput(true);
        http.connect();

        out = http.getOutputStream();
        out.write(params.getBytes("UTF-8"));
        out.flush();

        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 POST url=[%s] param=[%s] due to fail.", url, params), e);
    } finally {

        if (null != out) {
            try {
                out.close();
            } catch (IOException e) {
                logger.error(String.format("HTTP POST url=[%s] param=[%s]  close outputstream due to fail.",
                        url, params), e);
            }
        }
        if (null != in) {
            try {
                in.close();
            } catch (IOException e) {
                logger.error(String.format("HTTP POST url=[%s] param=[%s] close inputstream due to fail.", url,
                        params), e);
            }
        }

        if (http != null) {
            // 
            http.disconnect();

        }
    }
    return StringUtils.EMPTY;
}

From source file:test.integ.be.fedict.trust.SSLTrustValidatorTest.java

@Test
public void testValidation() throws Exception {
    Proxy proxy = Proxy.NO_PROXY;
    // Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
    // "proxy.yourict.net", 8080));
    NetworkConfig networkConfig = null; // new
    // NetworkConfig("proxy.yourict.net",
    // 8080);// w ww  .j  a v a 2s  .c  o  m
    // URL url = new URL("https://eid.belgium.be/"); // OK
    // URL url = new URL("https://www.fortisbanking.be"); // OK
    // URL url = new URL("https://www.e-contract.be/"); // OK
    // URL url = new URL("https://idp.services.belgium.be"); // OK
    // URL url = new URL("https://idp.int.belgium.be"); // OK
    //URL url = new URL("https://test.eid.belgium.be/");
    URL url = new URL("https://www.cloudflare.com/");

    // URL url = new URL("https://www.facebook.com");
    // URL url = new URL("https://www.twitter.com");
    // URL url = new URL("https://www.mozilla.org");
    // URL url = new URL("https://www.verisign.com/");
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(proxy);
    connection.connect();
    Certificate[] serverCertificates = connection.getServerCertificates();
    List<X509Certificate> certificateChain = new LinkedList<>();
    for (Certificate certificate : serverCertificates) {
        X509Certificate x509Cert = (X509Certificate) certificate;
        certificateChain.add(x509Cert);
        LOG.debug("certificate subject: " + x509Cert.getSubjectX500Principal());
        LOG.debug("certificate issuer: " + x509Cert.getIssuerX500Principal());
    }

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate rootCertificate = (X509Certificate) certificateFactory.generateCertificate(
            SSLTrustValidatorTest.class.getResourceAsStream("/ecc/AddTrustExternalCARoot.crt"));
    certificateChain.add(rootCertificate);

    MemoryCertificateRepository certificateRepository = new MemoryCertificateRepository();
    certificateRepository.addTrustPoint(certificateChain.get(certificateChain.size() - 1));

    //certificateRepository.addTrustPoint(rootCertificate);
    TrustValidator trustValidator = new TrustValidator(certificateRepository);
    trustValidator.setAlgorithmPolicy(new AlgorithmPolicy() {

        @Override
        public void checkSignatureAlgorithm(String signatureAlgorithm, Date validationDate)
                throws SignatureException {
            LOG.debug("signature algo: " + signatureAlgorithm);
            // allow all
        }
    });

    // next is kind of a default trust linked pattern.
    TrustValidatorDecorator trustValidatorDecorator = new TrustValidatorDecorator(networkConfig);
    trustValidatorDecorator.addDefaultTrustLinkerConfig(trustValidator);

    // operate
    trustValidator.isTrusted(certificateChain);
}

From source file:org.aankor.animenforadio.api.WebsiteGate.java

private void fetchCookies() throws IOException {
    if (phpSessID.equals("")) {
        URL url = new URL("https://www.animenfo.com/radio/index.php");
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.connect();
        updateCookies(con);//  ww  w .j  a v a2s  .  com
    }
}

From source file:com.jrummyapps.android.safetynet.SafetyNetHelper.java

/**
 * Validate the SafetyNet response using the Android Device Verification API. This API performs a validation check on
 * the JWS message returned from the SafetyNet service.
 *
 * <b>Important:</b> This use of the Android Device Verification API only validates that the provided JWS message was
 * received from the SafetyNet service. It <i>does not</i> verify that the payload data matches your original
 * compatibility check request./*w w  w.  ja v a2 s  . com*/
 *
 * @param jws
 *     The output of {@link SafetyNetApi.AttestationResult#getJwsResult()}.
 * @param apiKey
 *     The Android Device Verification API key
 * @return {@code true} if the provided JWS message was received from the SafetyNet service.
 * @throws SafetyNetError
 *     if an error occurs while verifying the JSON Web Signature.
 */
public static boolean validate(@NonNull String jws, @NonNull String apiKey) throws SafetyNetError {
    try {
        URL verifyApiUrl = new URL(GOOGLE_VERIFICATION_URL + apiKey);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        TrustManager[] defaultTrustManagers = trustManagerFactory.getTrustManagers();
        TrustManager[] trustManagers = Arrays.copyOf(defaultTrustManagers, defaultTrustManagers.length + 1);
        trustManagers[defaultTrustManagers.length] = new GoogleApisTrustManager();

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, null);

        HttpsURLConnection urlConnection = (HttpsURLConnection) verifyApiUrl.openConnection();
        urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-Type", "application/json");

        JSONObject requestJson = new JSONObject();
        requestJson.put("signedAttestation", jws);
        byte[] outputInBytes = requestJson.toString().getBytes("UTF-8");
        OutputStream os = urlConnection.getOutputStream();
        os.write(outputInBytes);
        os.close();

        urlConnection.connect();
        InputStream is = urlConnection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        for (String line = reader.readLine(), nl = ""; line != null; line = reader.readLine(), nl = "\n") {
            sb.append(nl).append(line);
        }

        return new JSONObject(sb.toString()).getBoolean("isValidSignature");
    } catch (Exception e) {
        throw new SafetyNetError(e);
    }
}

From source file:com.gson.util.HttpKit.java

/**
 * ?http?// w w  w .j a v a 2  s  . co  m
 * @param url
 * @param method
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws KeyManagementException
 */
private static HttpsURLConnection initHttps(String url, String method, Map<String, String> headers)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    TrustManager[] tm = { new MyX509TrustManager() };
    System.setProperty("https.protocols", "SSLv3");
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new java.security.SecureRandom());
    // SSLContextSSLSocketFactory  
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    URL _url = new URL(url);
    HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
    // ??
    http.setHostnameVerifier(new HttpKit().new TrustAnyHostnameVerifier());
    // 
    http.setConnectTimeout(25000);
    // ? --??
    http.setReadTimeout(25000);
    http.setRequestMethod(method);
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    http.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
    if (null != headers && !headers.isEmpty()) {
        for (Entry<String, String> entry : headers.entrySet()) {
            http.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }
    http.setSSLSocketFactory(ssf);
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    return http;
}