下面列出了怎么用javax.net.ssl.HttpsURLConnection的API类实例代码及写法,或者点击链接到github查看源代码。
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();
}
/**
* 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;
}
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);
}
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;
}
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");
}
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;
}
/**
* 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);
}
}
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();
}
/**
* 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;
}
/**
* 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);
}
}
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();
}
/**
* 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;
}
/**
* 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;
}
/**
* 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);
}
}
@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));
}
}
/**
* 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;
}
@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));
}
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();
}
/**
* 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 :)
}
@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();
}
/**
* 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 :)
}
@AfterClass
public static void stopProxy() throws Exception {
if (isUsingMockServer()) {
mockServer.stop();
proxy.dumpToLogAsJava();
proxy.stop();
HttpsURLConnection.setDefaultSSLSocketFactory(previousFactory);
}
}
/**
* 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();
}
/**
* 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);
}
/**
* 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);
}
/**
* 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;
}
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();
}
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;
}
/**
* 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;
}
/**
* 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;
}