javax.net.ssl.HttpsURLConnection Java Examples

The following examples show how to use javax.net.ssl.HttpsURLConnection. 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 Project: jdk8u60   Author: chenghanpeng   File: HttpsCreateSockTest.java    License: 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 Project: webdsl   Author: webdsl   File: URLType.java    License: Apache License 2.0 7 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 #3
Source Project: AndroidWallet   Author: Cocos-BCX   File: SslUtils.java    License: GNU General Public License v3.0 7 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 #4
Source Project: jdk8u_jdk   Author: JetBrains   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 #5
Source Project: developer-studio   Author: wso2   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 #6
Source Project: jdk8u-jdk   Author: lambdalab-mirror   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 #7
Source Project: AppleWifiNlpBackend   Author: microg   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 #8
Source Project: bcm-android   Author: bcmapp   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 #9
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   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 #10
Source Project: FeedListViewDemo   Author: bxbxbai   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 #11
Source Project: crosswalk-cordova-android   Author: crosswalk-project   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 #12
Source Project: product-emm   Author: wso2-attic   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 #13
Source Project: bitshares_wallet   Author: bituniverse   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 #14
Source Project: itracing2   Author: sylvek   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 #15
Source Project: barterli_android   Author: barterli   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 #16
Source Project: helios   Author: spotify   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 #17
Source Project: ecs-cf-service-broker   Author: thecodeteam   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 #18
Source Project: FunnyGuilds   Author: FunnyGuilds   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 #19
Source Project: constellation   Author: constellation-app   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 #20
Source Project: Skript   Author: SkriptLang   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 #21
Source Project: openerp-java-api   Author: DeBortoliWines   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 #22
Source Project: UhcCore   Author: Mezy   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 #23
Source Project: CrossBow   Author: patrick-doyle   File: HurlStack.java    License: Apache License 2.0 5 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 #24
Source Project: constellation   Author: constellation-app   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   Author: constellation-app   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   Author: xyqfer   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
Source Project: OneNoteAPISampleAndroid   Author: OneNoteDev   File: SendPageCreateAsyncTask.java    License: Apache License 2.0 5 votes vote down vote up
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
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: HttpClientTransport.java    License: GNU General Public License v2.0 5 votes vote down vote up
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   Author: Thinkmill   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   Author: gregallensworth   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;
}