网址/网址连接
Java 与 js 有着根本的不同。
其中一个区别是 java 是阻塞/同步的,这意味着默认方式是等待请求:
已知/可信证书或 HTTP
final URL url=new URL("url here");//create url
//Open an InputStream (binary) to the URL
//Convert it to a reader(text)
//Use buffering
try(BufferedReader br=new BufferedReader (new InputStreamReader(url.openStream(),StandardCharsets.UTF_8))){
br.lines().forEach(System.out::println);//print all lines
}catch(IOException e){
//Error handling
}
try-with-resources 语句会在不再需要资源时自动关闭它们。
这样做很重要,这样您就不会发生资源泄漏。
自签名/自定义证书
如this answer 中所述,您可以配置TrustStore 以添加自定义证书:
//Load certificate
File crtFile = new File("server.crt");
Certificate certificate = CertificateFactory.getInstance("X.509").generateCertificate(new FileInputStream(crtFile));
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("server", certificate);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
final URL url=new URL("url here");//create url
HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();//open a connection
connection.setSSLSocketFactory(sslContext.getSocketFactory());
//Open an InputStream (binary) to the URL
//Convert it to a reader(text)
//Use buffering
try(BufferedReader br=new BufferedReader (new InputStreamReader(connection.getInputStream(),StandardCharsets.UTF_8))){
br.lines().forEach(System.out::println);//print all lines
}catch(IOException e){
//Error handling
}
HttpClient
如果您使用 Java 11 或更新版本,您还可以尝试使用异步 HttpClient,如 here 所述。
这更类似于 JS 的方式。
已知/可信证书或 HTTP
HttpClient client = HttpClient.newHttpClient();//create the HTTPClient
HttpRequest request = HttpRequest.newBuilder()//create a request object, GET is the default
.uri(URI.create("url here"))//set the url
.build();//build the request object
client.sendAsync(request, BodyHandlers.ofString())//send the request in a background thread (fetch() in your code)
.thenApply(HttpResponse::body)//get the body as a string (.then(r=>r.text()) in your code))
.thenAccept(System.out::println);//print it (.then(console.log) in your code)
这种方法与您的 JS 示例一样是异步的。
自签名/自定义证书
如果您想使用自定义证书,可以使用sslContect 方法,如here:
//Load certificate
File crtFile = new File("server.crt");
Certificate certificate = CertificateFactory.getInstance("X.509").generateCertificate(new FileInputStream(crtFile));
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("server", certificate);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
//Execute the request
HttpClient client = HttpClient.newBuilder()//create a builder for the HttpClient
.sslContext(sslContext)//set the SSL context
.build();//build the HttpClient
HttpRequest request = HttpRequest.newBuilder()//create a request object, GET is the default
.uri(URI.create("url here"))//set the url
.build();//build the request object
client.sendAsync(request, BodyHandlers.ofString())//send the request in a background thread (fetch() in your code)
.thenApply(HttpResponse::body)//get the body as a string (.then(r=>r.text()) in your code))
.thenAccept(System.out::println);//print it (.then(console.log) in your code)
外部库
第三种可能性是使用像OkHttp这样的外部库。