Java Code Examples for javax.net.ssl.HttpsURLConnection

The following examples show how to use javax.net.ssl.HttpsURLConnection. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
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 Project: CrossBow   Source File: HurlStack.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Opens an {@link HttpURLConnection} with parameters.
 * @param url
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);

    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory);
    }

    return connection;
}
 
Example 3
Source Project: webdsl   Source File: URLType.java    License: Apache License 2.0 6 votes vote down vote up
protected static void setAcceptAllVerifier(HttpsURLConnection connection) throws NoSuchAlgorithmException, KeyManagementException {

        // Create the socket factory.
        // Reusing the same socket factory allows sockets to be
        // reused, supporting persistent connections.
        if( null == sslSocketFactory) {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, ALL_TRUSTING_TRUST_MANAGER, new java.security.SecureRandom());
            sslSocketFactory = sc.getSocketFactory();
        }

        connection.setSSLSocketFactory(sslSocketFactory);

        // Since we may be using a cert with a different name, we need to ignore
        // the hostname as well.
        connection.setHostnameVerifier(ALL_TRUSTING_HOSTNAME_VERIFIER);
    }
 
Example 4
Source Project: developer-studio   Source File: EclipseSWTTrustManager.java    License: Apache License 2.0 6 votes vote down vote up
public static void initiate() {
	// if (initiated) return;
	SSLContext sc;
	try {
		TrustManager[] trustAllCerts = new TrustManager[] { new EclipseSWTTrustManager() };
		sc = SSLContext.getInstance("SSL");
		sc.init(null, trustAllCerts, new java.security.SecureRandom());
		HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		HostnameVerifier allHostsValid = new HostnameVerifier() {
			public boolean verify(String hostname, SSLSession session) {
				return true;
			}
		};
		HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
	} catch (Exception e) {
		log.error(e.getMessage(),e);
	}
	initiated = true;
}
 
Example 5
Source Project: jdk8u-jdk   Source File: HttpsSocketFacTest.java    License: 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() + "/test6614957/");
    System.out.println("trying to connect to " + url + "...");

    HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
    SimpleSSLSocketFactory sssf = new SimpleSSLSocketFactory();
    uc.setSSLSocketFactory(sssf);
    uc.setHostnameVerifier(new AllHostnameVerifier());
    InputStream is = uc.getInputStream();

    byte[] ba = new byte[1024];
    int read = 0;
    while ((read = is.read(ba)) != -1) {
        System.out.println(new String(ba, 0, read));
    }

    System.out.println("SimpleSSLSocketFactory.socketCreated = " + sssf.socketCreated);
    System.out.println("SimpleSSLSocketFactory.socketWrapped = " + sssf.socketWrapped);

    if (!sssf.socketCreated)
        throw new RuntimeException("Failed: Socket Factory not being called to create Socket");
}
 
Example 6
Source Project: AppleWifiNlpBackend   Source File: LocationRetriever.java    License: Apache License 2.0 6 votes vote down vote up
public Collection<Location> retrieveLocations(String... macs) throws IOException {
    Request request = createRequest(macs);
    byte[] byteb = request.toByteArray();
    byte[] bytes = combineBytes(APPLE_MAGIC_BYTES, byteb, (byte) byteb.length);
    HttpsURLConnection connection = createConnection();
    prepareConnection(connection, bytes.length);
    OutputStream out = connection.getOutputStream();
    out.write(bytes);
    out.flush();
    out.close();
    InputStream in = connection.getInputStream();
    in.skip(10);
    Response response = wire.parseFrom(readStreamToEnd(in), Response.class);
    in.close();
    Collection<Location> locations = new ArrayList<Location>();
    for (Response.ResponseWifi wifi : response.wifis) {
        locations.add(fromResponseWifi(wifi));
    }
    return locations;
}
 
Example 7
Source Project: bcm-android   Source File: SslUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Makes an URL connection to accept a server-side certificate with specific
 * thumbprint and ignore host name verification. This is useful and safe if
 * you have a client with a hard coded well-known certificate
 *
 * @param connection       The connection to configure
 * @param serverThumbprint The X509 thumbprint of the server side certificate
 */
public static void configureTrustedCertificate(URLConnection connection, final String serverThumbprint) {
    if (!(connection instanceof HttpsURLConnection)) {
        return;
    }

    HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) connection;

    if (httpsUrlConnection.getHostnameVerifier() != HOST_NAME_VERIFIER_ACCEPT_ALL) {
        httpsUrlConnection.setHostnameVerifier(HOST_NAME_VERIFIER_ACCEPT_ALL);
    }
    SSLSocketFactory sslSocketFactory = getSsLSocketFactory(serverThumbprint);
    if (httpsUrlConnection.getSSLSocketFactory() != sslSocketFactory) {
        // SSL socket factory is nonnull in Android Q
        httpsUrlConnection.setSSLSocketFactory(sslSocketFactory);
    }
}
 
Example 8
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 Project: FeedListViewDemo   Source File: HurlStack.java    License: MIT License 6 votes vote down vote up
/**
 * Opens an {@link HttpURLConnection} with parameters.
 * @param url
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);

    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory);
    }

    return connection;
}
 
Example 10
Source Project: AndroidWallet   Source File: SslUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Makes an URL connection to accept a server-side certificate with specific
 * thumbprint and ignore host name verification. This is useful and safe if
 * you have a client with a hard coded well-known certificate
 * 
 * @param connection
 *           The connection to configure
 * @param serverThumbprint
 *           The X509 thumbprint of the server side certificate
 */
public static void configureTrustedCertificate(URLConnection connection, final String serverThumbprint) {
   if (!(connection instanceof HttpsURLConnection)) {
      return;
   }

   HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) connection;

   if (httpsUrlConnection.getHostnameVerifier() != HOST_NAME_VERIFIER_ACCEPT_ALL) {
      httpsUrlConnection.setHostnameVerifier(HOST_NAME_VERIFIER_ACCEPT_ALL);
   }
   SSLSocketFactory sslSocketFactory = getSsLSocketFactory(serverThumbprint);
   if (httpsUrlConnection.getSSLSocketFactory() != sslSocketFactory) {
      httpsUrlConnection.setSSLSocketFactory(sslSocketFactory);
   }
}
 
Example 11
Source Project: jdk8u60   Source File: HttpsCreateSockTest.java    License: 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 12
Source Project: crosswalk-cordova-android   Source File: OkHttpClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a shallow copy of this OkHttpClient that uses the system-wide default for
 * each field that hasn't been explicitly configured.
 */
private OkHttpClient copyWithDefaults() {
  OkHttpClient result = new OkHttpClient(this);
  result.proxy = proxy;
  result.proxySelector = proxySelector != null ? proxySelector : ProxySelector.getDefault();
  result.cookieHandler = cookieHandler != null ? cookieHandler : CookieHandler.getDefault();
  result.responseCache = responseCache != null ? responseCache : ResponseCache.getDefault();
  result.sslSocketFactory = sslSocketFactory != null
      ? sslSocketFactory
      : HttpsURLConnection.getDefaultSSLSocketFactory();
  result.hostnameVerifier = hostnameVerifier != null
      ? hostnameVerifier
      : OkHostnameVerifier.INSTANCE;
  result.authenticator = authenticator != null
      ? authenticator
      : HttpAuthenticator.SYSTEM_DEFAULT;
  result.connectionPool = connectionPool != null ? connectionPool : ConnectionPool.getDefault();
  result.followProtocolRedirects = followProtocolRedirects;
  result.transports = transports != null ? transports : DEFAULT_TRANSPORTS;
  result.connectTimeout = connectTimeout;
  result.readTimeout = readTimeout;
  return result;
}
 
Example 13
Source Project: product-emm   Source File: HurlStack.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Opens an {@link HttpURLConnection} with parameters.
 * @param url
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);

    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory);
    }

    return connection;
}
 
Example 14
Source Project: bitshares_wallet   Source File: SslUtils.java    License: MIT License 6 votes vote down vote up
/**
 * Makes an URL connection to accept a server-side certificate with specific
 * thumbprint and ignore host name verification. This is useful and safe if
 * you have a client with a hard coded well-known certificate
 * 
 * @param connection
 *           The connection to configure
 * @param serverThumbprint
 *           The X509 thumbprint of the server side certificate
 */
public static void configureTrustedCertificate(URLConnection connection, final String serverThumbprint) {
   if (!(connection instanceof HttpsURLConnection)) {
      return;
   }

   HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) connection;

   if (httpsUrlConnection.getHostnameVerifier() != HOST_NAME_VERIFIER_ACCEPT_ALL) {
      httpsUrlConnection.setHostnameVerifier(HOST_NAME_VERIFIER_ACCEPT_ALL);
   }
   SSLSocketFactory sslSocketFactory = getSsLSocketFactory(serverThumbprint);
   if (httpsUrlConnection.getSSLSocketFactory() != sslSocketFactory) {
      httpsUrlConnection.setSSLSocketFactory(sslSocketFactory);
   }
}
 
Example 15
Source Project: itracing2   Source File: CustomAction.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    final String address = intent.getStringExtra(Devices.ADDRESS);
    final String source = intent.getStringExtra(Devices.SOURCE);
    final String action = Preferences.getCustomAction(context, address, source);

    if (action.startsWith("http://")) {
        new CallUrl<>(action, "address=" + address + "&source=" + source).start();
    }

    if (action.startsWith("https://")) {
        new CallUrl<HttpsURLConnection>(action, "address=" + address + "&source=" + source).start();
    }

    if (action.startsWith("mqtt://")) {
        new PublishMQTT(action, address + "," + source).start();
    }

    if (action.startsWith("tel:")) {
        new Phone(context, action).start();
    }

    if (!action.isEmpty()) {
        context.sendBroadcast(new Intent(action));
    }
}
 
Example 16
Source Project: barterli_android   Source File: HurlStack.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Opens an {@link HttpURLConnection} with parameters.
 * 
 * @param url
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request)
                throws IOException {

    HttpURLConnection connection = createConnection(url);

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);

    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection)
                        .setSSLSocketFactory(mSslSocketFactory);
    }

    return connection;
}
 
Example 17
Source Project: helios   Source File: AuthenticatingHttpConnectorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testOneIdentity_ResponseIsOk() throws Exception {

  final AgentProxy proxy = mock(AgentProxy.class);
  final Identity identity = mockIdentity();

  final AuthenticatingHttpConnector authConnector =
      createAuthenticatingConnector(Optional.of(proxy), ImmutableList.of(identity));

  final String path = "/another/one";

  final HttpsURLConnection connection = mock(HttpsURLConnection.class);
  when(connector.connect(argThat(matchesAnyEndpoint(path)),
      eq(method),
      eq(entity),
      eq(headers))
  ).thenReturn(connection);
  when(connection.getResponseCode()).thenReturn(200);

  final URI uri = new URI("https://helios" + path);

  authConnector.connect(uri, method, entity, headers);

  verify(connector).setExtraHttpsHandler(isA(HttpsHandler.class));
}
 
Example 18
Source Project: ecs-cf-service-broker   Source File: Connection.java    License: Apache License 2.0 5 votes vote down vote up
private Client buildJerseyClient() throws EcsManagementClientException {
    ClientBuilder builder;
    if (certificate != null) {
        // Disable host name verification. Should be able to configure the
        // ECS certificate with the correct host name to avoid this.
        HostnameVerifier hostnameVerifier = getHostnameVerifier();
        HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
        builder = ClientBuilder.newBuilder()
                .register(hostnameVerifier);
        builder.sslContext(getSSLContext());
    } else {
        builder = ClientBuilder.newBuilder();
    }
    return builder.build();
}
 
Example 19
Source Project: FunnyGuilds   Source File: BStats.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JSONObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("InvitationPersistenceHandler cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
 
Example 20
Source Project: constellation   Source File: NifiClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public HttpsURLConnection makePostConnection(String url, Map<String, String> params) throws IOException {
    final URL nifiUrl = generateUrl(url, params);
    return HttpsConnection
            .withUrl(nifiUrl.toString())
            .doOutput()
            .acceptJson()
            .addRequestProperty(HttpsConnection.CONTENT_TYPE, HttpsConnection.APPLICATION_FORM)
            .addRequestProperty("flexloader.type", "flowfile-v3")
            .withReadTimeout(60 * 1000)
            .post();
}
 
Example 21
Source Project: Skript   Source File: Metrics.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JSONObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
 
Example 22
Source Project: openerp-java-api   Source File: SessionTest.java    License: Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void stopProxy() throws Exception {
	if (isUsingMockServer()) {
		mockServer.stop();
		proxy.dumpToLogAsJava();
		proxy.stop();
		HttpsURLConnection.setDefaultSSLSocketFactory(previousFactory);
	}
}
 
Example 23
Source Project: UhcCore   Source File: FileUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Downloads a file from the internet
 * @param url Url of the file / api
 * @param path Path do the destination of the file
 * @throws IOException Thrown when file fails to download
 */
public static void downloadFile(URL url, File path) throws IOException{
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.connect();

    InputStream in = connection.getInputStream();

    Files.copy(in, Paths.get(path.toURI()));

    in.close();
    connection.disconnect();
}
 
Example 24
Source Project: constellation   Source File: RestClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Post method which will convert the {@code params} to a JSON body. At the
 * moment this method only supports a simple JSON object. That is, it does
 * not convert arrays into JSON.
 *
 * @param url The URL to request
 * @param params A simple key/value pair in which values do not contain
 * Arrays, Sets etc
 *
 * @throws IOException
 */
public void post(final String url, final Map<String, String> params) 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(generateJsonFromFlatMap(params));
            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 25
Source Project: constellation   Source File: RestClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 26
Source Project: reader   Source File: FileTransfer.java    License: MIT License 5 votes vote down vote up
/**
 * This function will install a trust manager that will blindly trust all SSL
 * certificates.  The reason this code is being added is to enable developers
 * to do development using self signed SSL certificates on their web server.
 *
 * The standard HttpsURLConnection class will throw an exception on self
 * signed certificates if this code is not run.
 */
private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
    // Install the all-trusting trust manager
    SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
    try {
        // Install our all trusting manager
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLSocketFactory newFactory = sc.getSocketFactory();
        connection.setSSLSocketFactory(newFactory);
    } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
    return oldFactory;
}
 
Example 27
private void postMultipartRequest(String endpoint) throws Exception {

		mUrlConnection = (HttpsURLConnection) ( new URL(endpoint)).openConnection();
		mUrlConnection.setDoOutput(true);
		mUrlConnection.setRequestMethod("POST");
		mUrlConnection.setDoInput(true);
		mUrlConnection.setRequestProperty("Connection", "Keep-Alive");
		mUrlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
		mUrlConnection.setRequestProperty("Authorization", "Bearer " + mAccessToken);
		mUrlConnection.connect();
		mOutputStream = mUrlConnection.getOutputStream();
	}
 
Example 28
protected boolean checkHTTPS(HttpURLConnection connection) {
    if (connection instanceof HttpsURLConnection) {

        // TODO The above property needs to be removed in future version as the semantics of this property are not preoperly defined.
        // One should use JAXWSProperties.HOSTNAME_VERIFIER to control the behavior

        // does the client want client hostname verification by the service
        String verificationProperty =
            (String) context.invocationProperties.get(HOSTNAME_VERIFICATION_PROPERTY);
        if (verificationProperty != null) {
            if (verificationProperty.equalsIgnoreCase("true")) {
                ((HttpsURLConnection) connection).setHostnameVerifier(new HttpClientVerifier());
            }
        }

        // Set application's HostNameVerifier for this connection
        HostnameVerifier verifier =
            (HostnameVerifier) context.invocationProperties.get(JAXWSProperties.HOSTNAME_VERIFIER);
        if (verifier != null) {
            ((HttpsURLConnection) connection).setHostnameVerifier(verifier);
        }

        // Set application's SocketFactory for this connection
        SSLSocketFactory sslSocketFactory =
            (SSLSocketFactory) context.invocationProperties.get(JAXWSProperties.SSL_SOCKET_FACTORY);
        if (sslSocketFactory != null) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory);
        }

        return true;
    }
    return false;
}
 
Example 29
Source Project: reacteu-app   Source File: FileTransfer.java    License: MIT License 5 votes vote down vote up
/**
 * This function will install a trust manager that will blindly trust all SSL
 * certificates.  The reason this code is being added is to enable developers
 * to do development using self signed SSL certificates on their web server.
 *
 * The standard HttpsURLConnection class will throw an exception on self
 * signed certificates if this code is not run.
 */
private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
    // Install the all-trusting trust manager
    SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
    try {
        // Install our all trusting manager
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLSocketFactory newFactory = sc.getSocketFactory();
        connection.setSSLSocketFactory(newFactory);
    } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
    return oldFactory;
}
 
Example 30
Source Project: L.TileLayer.Cordova   Source File: FileTransfer.java    License: MIT License 5 votes vote down vote up
/**
 * This function will install a trust manager that will blindly trust all SSL
 * certificates.  The reason this code is being added is to enable developers
 * to do development using self signed SSL certificates on their web server.
 *
 * The standard HttpsURLConnection class will throw an exception on self
 * signed certificates if this code is not run.
 */
private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
    // Install the all-trusting trust manager
    SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
    try {
        // Install our all trusting manager
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLSocketFactory newFactory = sc.getSocketFactory();
        connection.setSSLSocketFactory(newFactory);
    } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
    return oldFactory;
}
 
Example 31
Source Project: olat   Source File: OnyxReporterWebserviceClient.java    License: 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 32
Source Project: hadoop   Source File: Fetcher.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
protected synchronized void openConnection(URL url)
    throws IOException {
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  if (sslShuffle) {
    HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
    try {
      httpsConn.setSSLSocketFactory(sslFactory.createSSLSocketFactory());
    } catch (GeneralSecurityException ex) {
      throw new IOException(ex);
    }
    httpsConn.setHostnameVerifier(sslFactory.getHostnameVerifier());
  }
  connection = conn;
}
 
Example 33
Source Project: lemon   Source File: CdnUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void configHttps(HttpURLConnection conn) throws Exception {
    TrustManager[] tm = { new TrustAllX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");

    sslContext.init(null, tm, new java.security.SecureRandom());

    SSLSocketFactory ssf = sslContext.getSocketFactory();

    // ssf.setHostnameVerifier(new TrustAllHostnameVerifier());
    ((HttpsURLConnection) conn).setSSLSocketFactory(ssf);
    ((HttpsURLConnection) conn)
            .setHostnameVerifier(new TrustAllHostnameVerifier());
}
 
Example 34
Source Project: acunetix-plugin   Source File: Engine.java    License: MIT License 5 votes vote down vote up
private HttpsURLConnection openConnection(String endpoint, String method, String contentType) throws IOException {
    URL url = new URL(endpoint);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setRequestMethod(method);
    connection.setRequestProperty("Content-Type", contentType);
    connection.setRequestProperty("User-Agent", "Mozilla/5.0");
    connection.addRequestProperty("X-AUTH", apiKey);
    return connection;
}
 
Example 35
public static void disable() {
    try {
        SSLContext sslc = SSLContext.getInstance("TLS");
        TrustManager[] trustManagerArray = { new NullX509TrustManager() };
        sslc.init(null, trustManagerArray, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new NullHostnameVerifier());
    } catch(Exception e) {
        e.printStackTrace();
    }
}
 
Example 36
Source Project: Hands-Chopping   Source File: SankoGetGameDetailTask.java    License: 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];
    StringBuilder builder = new StringBuilder();
    try {
        URL url=new URL("https://www.sonkwo.com/api/products/"+product_id+".json?locale=js&sonkwo_version=1&sonkwo_client=web&_="+String.valueOf(System.currentTimeMillis()));
        HttpsURLConnection httpsURLConnection=(HttpsURLConnection)url.openConnection();

        httpsURLConnection.setRequestMethod("GET");
        httpsURLConnection.setRequestProperty("Accept","application/vnd.sonkwo.v5+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 37
Source Project: DavidWebb   Source File: Webb.java    License: MIT License 5 votes vote down vote up
private void prepareSslConnection(HttpURLConnection connection) {
    if ((hostnameVerifier != null || sslSocketFactory != null) && connection instanceof HttpsURLConnection) {
        HttpsURLConnection sslConnection = (HttpsURLConnection) connection;
        if (hostnameVerifier != null) {
            sslConnection.setHostnameVerifier(hostnameVerifier);
        }
        if (sslSocketFactory != null) {
            sslConnection.setSSLSocketFactory(sslSocketFactory);
        }
    }
}
 
Example 38
Source Project: acunetix-plugin   Source File: Engine.java    License: MIT License 5 votes vote down vote up
private Resp doGet(String urlStr) throws IOException {
    HttpsURLConnection connection = openConnection(urlStr);
    try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"))) {
        String inputLine;
        StringBuilder resbuf = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            resbuf.append(inputLine);
        }
        Resp resp = new Resp();
        resp.respCode = connection.getResponseCode();
        resp.jso = JSONObject.fromObject(resbuf.toString());
        return resp;
    }
}
 
Example 39
Source Project: eLong-OpenAPI-JAVA-demo   Source File: Demo.java    License: Apache License 2.0 5 votes vote down vote up
private static void trustAllHttpsCertificates() throws Exception {  
    javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];  
    javax.net.ssl.TrustManager tm = new miTM();  
    trustAllCerts[0] = tm;  
    javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext  
            .getInstance("SSL");  
    sc.init(null, trustAllCerts, null);  
    javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc  
            .getSocketFactory());  
}
 
Example 40
Source Project: hadoop   Source File: TestSSLHttpServer.java    License: Apache License 2.0 5 votes vote down vote up
private static String readOut(URL url) throws Exception {
  HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
  conn.setSSLSocketFactory(clientSslFactory.createSSLSocketFactory());
  InputStream in = conn.getInputStream();
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  IOUtils.copyBytes(in, out, 1024);
  return out.toString();
}