Java Code Examples for javax.net.ssl.HttpsURLConnection#connect()

The following examples show how to use javax.net.ssl.HttpsURLConnection#connect() . 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 vote down vote up
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: ExprUrlSSLSerialNumber.java    From skUtilities with GNU General Public License v3.0 6 votes vote down vote up
@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 3
Source File: HttpsCreateSockTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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 jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
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: NetworkTools.java    From MyBox with Apache License 2.0 6 votes vote down vote up
public static File httpsPage(String address) {
    try {
        URL url = new URL(address);
        File pageFile = FileTools.getTempFile(".htm");
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        SSLContext sc = SSLContext.getInstance(CommonValues.HttpsProtocal);
        sc.init(null, trustAllManager(), new SecureRandom());
        connection.setSSLSocketFactory(sc.getSocketFactory());
        connection.setHostnameVerifier(trustAllVerifier());
        connection.connect();
        try ( BufferedInputStream inStream = new BufferedInputStream(connection.getInputStream());
                 BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(pageFile))) {
            byte[] buf = new byte[CommonValues.IOBufferLength];
            int len;
            while ((len = inStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
        }
        return pageFile;
    } catch (Exception e) {
        logger.error(e.toString());
        return null;
    }
}
 
Example 6
Source File: ExprUrlSSLVerifier.java    From skUtilities with GNU General Public License v3.0 6 votes vote down vote up
@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 7
Source File: HttpsCreateSockTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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 8
Source File: HttpsCreateSockTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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: HttpsCreateSockTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
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 10
Source File: HdfsProxy.java    From RDFS with Apache License 2.0 5 votes vote down vote up
private static boolean sendCommand(Configuration conf, String path)
    throws IOException {
  setupSslProps(conf);
  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 (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());
      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 true;
  }
  return false;
}
 
Example 11
Source File: HttpUtils.java    From mclauncher-api with MIT License 5 votes vote down vote up
/**
 * Execute a secured POST request
 * @param url URL to request
 * @param keyInput the secret key to be used
 * @param parameters Parameters in form <code>name=Tom&amp;password=pass123</code>. They needn't to be URL-encoded(it will be done automatically)
 * @return The result of request
 * @throws Exception I/O Exception, HTTP errors or invalid key
 */
public static String securePostWithKey(String url, InputStream keyInput, String parameters) throws Exception {
    URL u = new URL(url);
    HttpsURLConnection connection = (HttpsURLConnection) u.openConnection();
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("Content-Length", "" + parameters.getBytes().length);
    connection.setRequestProperty("Content-Language", "en-US");

    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    connection.connect();
    Certificate cert = connection.getServerCertificates()[0];
    byte[] serverKey = cert.getPublicKey().getEncoded();
    DataInputStream dis = new DataInputStream(keyInput);
    for (int i = 0; i < serverKey.length; ++i) {
        if (dis.readByte() != serverKey[i]) {
            throw new SecurityException("Invalid Server Key!");
        }
    }
    DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
    dos.writeBytes(URLEncoder.encode(parameters, "utf-8"));
    dos.flush();
    dos.close();

    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line;
    StringBuilder response = new StringBuilder();
    while ((line = br.readLine()) != null) {
        response = response.append(line).append('\r');
    }
    br.close();
    connection.disconnect();
    return response.toString();
}
 
Example 12
Source File: OnyxReporterWebserviceClient.java    From olat with Apache License 2.0 5 votes vote down vote up
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 13
Source File: HttpsImageProvider.java    From ureport with Apache License 2.0 5 votes vote down vote up
@Override
public InputStream getImage(String path) {
	try{
		URL url=new URL(path);
		HttpsURLConnection connection=(HttpsURLConnection)url.openConnection();
		connection.connect();
		InputStream inputStream=connection.getInputStream();
		return inputStream;
	}catch(Exception ex){
		throw new ReportException(ex);
	}
}
 
Example 14
Source File: SankoGetGameReview.java    From Hands-Chopping with Apache License 2.0 5 votes vote down vote up
@Override
protected String doInBackground(String... strings) {
    String[] parms=strings[0].split("&");
    String product_id=parms[0];
    String id=parms[1];
    String groupid=parms[2];
    StringBuilder builder = new StringBuilder();
    try {
        URL url=new URL("https://www.sonkwo.com/api/reviews.json?per=7&page=1&locale=js&sonkwo_version=1&sonkwo_client=web&group_id="+groupid+"&_="+String.valueOf(System.currentTimeMillis()));
        HttpsURLConnection httpsURLConnection=(HttpsURLConnection)url.openConnection();

        httpsURLConnection.setRequestMethod("GET");
        httpsURLConnection.setRequestProperty("Accept","application/vnd.sonkwo.v4+json");
        httpsURLConnection.setRequestProperty("Accept-Encoding","deflate, br");
        httpsURLConnection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.9,zh-TW;q=0.8");
        httpsURLConnection.setRequestProperty("Connection","keep-alive");
        httpsURLConnection.setRequestProperty("Host","www.sonkwo.com");
        httpsURLConnection.setRequestProperty("Referer","https://www.sonkwo.com/products/"+product_id+"?game_id="+id);
        httpsURLConnection.setRequestProperty("User-Agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36");
        httpsURLConnection.setRequestProperty("X-Requested-With","XMLHttpRequest");
        //httpsURLConnection.setRequestProperty("Cookie","_sonkwo_community_session=eCKQrQ4i8%2BqTX1PhnNSXTxNN1sIjkSe%2BS3agPmJbTJHS9mY3h3gite8fCRlVVP%2F6a%2Fj8g0oYYQ8YdIggPihUqIJ5fH2%2Fdoi5yXfwhXit1r5V6dr4Jxso3OX30iMN7s3ma1PHmKpHR5howHL9lk4mWi9H2ncfEBXde6lcvHPJ2H0C6w%3D%3D--N%2BsFOFFVlHE%2FDVUp--rsjifub42VFgFk5fC2hoWg%3D%3D; Hm_lvt_4abede90a75b2ba39a03e7a40fcec65f="+timestamp+"; Hm_lpvt_4abede90a75b2ba39a03e7a40fcec65f="+timestamp);

        httpsURLConnection.connect();
        if(httpsURLConnection.getResponseCode()==200){
            InputStream inputStream = null;

            if (null == inputStream) {
                inputStream = httpsURLConnection.getInputStream();
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line = null;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        }
    }catch (Exception e){
        e.printStackTrace();
    }
    return builder.toString();
}
 
Example 15
Source File: ClientAuthTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@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 16
Source File: HttpsTrustManager.java    From stategen with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void downLoadFromUrlHttps(String urlStr, String fileName,
        String savePath) throws Exception {
    // 创建SSLContext
    SSLContext sslContext = SSLContext.getInstance("SSL");
    TrustManager[] tm = { new HttpsTrustManager() };
    // 初始化
    sslContext.init(null, tm, new java.security.SecureRandom());
    // 获取SSLSocketFactory对象
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    // url对象
    URL url = new URL(urlStr);
    // 打开连接
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    /**
     * 这一步的原因: 当访问HTTPS的网址。您可能已经安装了服务器证书到您的JRE的keystore
     * 但是服务器的名称与证书实际域名不相等。这通常发生在你使用的是非标准网上签发的证书。
     * 
     * 解决方法:让JRE相信所有的证书和对系统的域名和证书域名。
     * 
     * 如果少了这一步会报错:java.io.IOException: HTTPS hostname wrong: should be <localhost>
     */
    conn.setHostnameVerifier(new HttpsTrustManager().new TrustAnyHostnameVerifier());
    // 设置一些参数
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    // 设置当前实例使用的SSLSoctetFactory
    conn.setSSLSocketFactory(ssf);
    conn.connect();
 
 
    // 得到输入流
    @Cleanup
    InputStream inputStream = conn.getInputStream();
    byte[] getData = readInputStream(inputStream);
    // 文件保存位置
    File saveDir = new File(savePath);
    if (!saveDir.exists()) {
        saveDir.mkdirs();
    }
    //输出流
    File file = new File(saveDir + File.separator + fileName);
    @Cleanup
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(getData);
}
 
Example 17
Source File: NamespaceOverrideMapper.java    From hawkular-metrics with Apache License 2.0 4 votes vote down vote up
private Map<String,String> getNamespaceMapping(Set<String> tenants) {
    Map<String,String> namespaceMap = new HashMap<>();

    if (tenants == null || tenants.isEmpty()) {
        return namespaceMap;
    }

    try {
        String path = "api/v1/namespaces";
        URL url = new URL(NamespaceHandler.KUBERNETES_MASTER_URL + "/" + path);

        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + token);

        // set to 0 which indicated an infinite timeout
        connection.setConnectTimeout(0);
        connection.setReadTimeout(0);

        connection.connect();
        int responseCode = connection.getResponseCode();

        if (responseCode == 200) {

            JsonFactory jsonFactory = new JsonFactory();
            jsonFactory.setCodec(new ObjectMapper());

            InputStream inputStream = connection.getInputStream();
            JsonParser jsonParser = jsonFactory.createParser(inputStream);

            JsonNode jsonNode = jsonParser.readValueAsTree();
            // When the connection is closed, the response is null
            if (jsonNode != null) {
                JsonNode items = jsonNode.get("items");
                if (items != null && items.isArray()) {
                    for (JsonNode project : items) {
                        JsonNode metaData = project.get("metadata");
                        String projectName = metaData.get("name").asText();
                        String projectID = metaData.get("uid").asText();

                        if (tenants.contains(projectName)) {
                            namespaceMap.put(projectID, projectName);
                        }
                    }
                }
            }

            jsonParser.close();
            inputStream.close();

        } else {
            log.error("Error getting metadata from the OpenShift Master (" + responseCode + "). This may mean the 'hawkular' user does not have permission to watch projects. Waiting 2 seconds and will try again.");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }


    } catch (IOException e) {
        log.error(e);
    }

    return namespaceMap;
}
 
Example 18
Source File: Spotify.java    From blade-player with GNU General Public License v3.0 4 votes vote down vote up
private void refreshSpotifyToken()
{
    try
    {
        URL apiUrl = new URL("https://accounts.spotify.com/api/token");
        HttpsURLConnection urlConnection = (HttpsURLConnection) apiUrl.openConnection();
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod("POST");

        //write POST parameters
        OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
        BufferedWriter writer = new BufferedWriter (new OutputStreamWriter(out, "UTF-8"));
        writer.write("grant_type=refresh_token&");
        writer.write("refresh_token=" + SPOTIFY_REFRESH_TOKEN + "&");
        writer.write("client_id=" + SPOTIFY_CLIENT_ID + "&");
        writer.write("client_secret=" + "3166d3b40ff74582b03cb23d6701c297");
        writer.flush();
        writer.close();
        out.close();

        urlConnection.connect();

        System.out.println("[BLADE] [AUTH-REFRESH] Result : " + urlConnection.getResponseCode() + " " + urlConnection.getResponseMessage());

        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String result = reader.readLine();
        reader.close();
        result = result.substring(1);
        result = result.substring(0, result.length()-1);
        String[] results = result.split(",");
        for(String param : results)
        {
            if(param.startsWith("\"access_token\":\""))
            {
                param = param.replaceFirst("\"access_token\":\"", "");
                param = param.replaceFirst("\"", "");
                SPOTIFY_USER_TOKEN = param;
                spotifyApi.setAccessToken(SPOTIFY_USER_TOKEN);
                SharedPreferences pref = LibraryService.appContext.getSharedPreferences(SettingsActivity.PREFERENCES_ACCOUNT_FILE_NAME, Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = pref.edit();
                editor.putString("spotify_token", SPOTIFY_USER_TOKEN);
                editor.commit();
            }
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}
 
Example 19
Source File: SSLv3Test.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSSLv3ServerNotAllowedByDefault() throws Exception {

    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = SSLv3Test.class.getResource("sslv3-client.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    System.setProperty("https.protocols", "SSLv3");

    URL service = new URL("https://localhost:" + PORT);
    HttpsURLConnection connection = (HttpsURLConnection) service.openConnection();

    connection.setHostnameVerifier(new DisableCNCheckVerifier());

    SSLContext sslContext = SSLContext.getInstance("SSL");

    KeyStore trustedCertStore = KeyStore.getInstance("jks");
    try (InputStream keystore = ClassLoaderUtils.getResourceAsStream("keys/Truststore.jks", SSLv3Test.class)) {
        trustedCertStore.load(keystore, null);
    }

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustedCertStore);
    TrustManager[] trustManagers = tmf.getTrustManagers();

    sslContext.init(null, trustManagers, new java.security.SecureRandom());
    connection.setSSLSocketFactory(sslContext.getSocketFactory());

    try {
        connection.connect();
        fail("Failure expected on an SSLv3 connection attempt");
    } catch (IOException ex) {
        // expected
    }

    System.clearProperty("https.protocols");

    bus.shutdown(true);
}
 
Example 20
Source File: Gateway.java    From gateway-android-sdk with Apache License 2.0 4 votes vote down vote up
GatewayMap executeGatewayRequest(GatewayRequest request) throws Exception {
    // init connection
    HttpsURLConnection c = createHttpsUrlConnection(request);

    // encode request data to json
    String requestData = gson.toJson(request.payload);

    // log request data
    logger.logRequest(c, requestData);

    // write request data
    if (requestData != null) {
        OutputStream os = c.getOutputStream();
        os.write(requestData.getBytes("UTF-8"));
        os.close();
    }

    // initiate the connection
    c.connect();

    String responseData = null;
    int statusCode = c.getResponseCode();
    boolean isStatusOk = (statusCode >= 200 && statusCode < 300);

    // if connection has output stream, get the data
    // socket time-out exceptions will be thrown here
    if (c.getDoInput()) {
        InputStream is = isStatusOk ? c.getInputStream() : c.getErrorStream();
        responseData = inputStreamToString(is);
        is.close();
    }

    c.disconnect();

    // log response
    logger.logResponse(c, responseData);

    // parse the response body
    GatewayMap response = new GatewayMap(responseData);

    // if response static is good, return response
    if (isStatusOk) {
        return response;
    }

    // otherwise, create a gateway exception and throw it
    String message = (String) response.get("error.explanation");
    if (message == null) {
        message = "An error occurred";
    }

    GatewayException exception = new GatewayException(message);
    exception.setStatusCode(statusCode);
    exception.setErrorResponse(response);

    throw exception;
}