对 Java 中任何 URL 的 HTTP(S) 请求
HTTP(S) request to any URL in Java
我需要向提供的用户发出 GET 请求 URL(可以是 http 或 https)
在Java我可以做的脚本中:
fetch(prompt()).then(r => r.text()).then(console.log)
Java 的等效代码是什么?
如何使用自定义证书?
URL/URLConnection
Java 与 js 根本不同。
其中一个区别是 java 是 blocking/synchronous,这意味着默认方式是等待请求:
known/trusted 证书或 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 语句会在不再需要时自动关闭资源。
这样做很重要,这样您就不会发生资源泄漏。
本人signed/custom证书
如 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 方法。
known/trusted 证书或 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 示例一样是异步的。
本人signed/custom证书
如果要使用自定义证书,可以使用sslContect
方法,如:
//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。
HttpURLConnection class from java.net package can be used to send
Java HTTP Request programmatically. Today we will learn how to use
HttpURLConnection in java program to send GET and POST requests and then print the response.
以下是使用 HttpURLConnection class.[=15= 发送 Java HTTP 请求需要遵循的步骤]
- 从 GET/POST URL 字符串创建 URL object。
- 在 URL object 的 returns 实例上调用 openConnection() 方法
HttpURL连接
- 在HttpURLConnection实例中设置请求方式,默认
值为 GET。
- 在 HttpURLConnection 实例上调用 setRequestProperty() 方法
设置请求 header 值,例如“User-Agent”和
“Accept-Language”等
- 我们可以调用getResponseCode()来获取响应HTTP代码。
这样我们就知道请求是否被成功处理或在那里
是否抛出任何 HTTP 错误消息。
- 对于GET,我们可以简单地使用Reader和InputStream来读取
响应并进行相应处理。
- 对于POST,在我们读取响应之前我们需要获取OutputStream
来自 HttpURLConnection 实例并将 POST 参数写入
它。
HttpURLConnection Example
基于上述步骤,下面的示例程序显示了 HttpURLConnection 发送 Java GET 和 POST 的用法请求。
JAVA CODE
package com.mr.rockerz.HttpUrlExample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionExample {
private static final String USER_AGENT = "Mozilla/5.0";
private static final String GET_URL = "https://localhost:9090/SpringMVCExample";
private static final String POST_URL = "https://localhost:9090/SpringMVCExample/home";
private static final String POST_PARAMS = "userName=Pankaj";
public static void main(String[] args) throws IOException {
sendGET();
System.out.println("GET DONE");
sendPOST();
System.out.println("POST DONE");
}
private static void sendGET() throws IOException {
URL obj = new URL(GET_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("GET request not worked");
}
}
private static void sendPOST() throws IOException {
URL obj = new URL(POST_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST request not worked");
}
}
}
当我们执行上面的程序时,我们得到以下响应。
GET Response Code :: 200
<html><head> <title>Home</title></head><body><h1> Hello world! </h1><P> The time on the server is March 6, 2015 9:31:04 PM IST. </P></body></html>
GET DONE
POST Response Code :: 200
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>User Home Page</title></head><body><h3>Hi Pankaj</h3></body></html>
POST DONE
如果您有任何疑问,请在评论中提问。
我需要向提供的用户发出 GET 请求 URL(可以是 http 或 https)
在Java我可以做的脚本中:
fetch(prompt()).then(r => r.text()).then(console.log)
Java 的等效代码是什么?
如何使用自定义证书?
URL/URLConnection
Java 与 js 根本不同。
其中一个区别是 java 是 blocking/synchronous,这意味着默认方式是等待请求:
known/trusted 证书或 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 语句会在不再需要时自动关闭资源。
这样做很重要,这样您就不会发生资源泄漏。
本人signed/custom证书
如 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 方法。
known/trusted 证书或 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 示例一样是异步的。
本人signed/custom证书
如果要使用自定义证书,可以使用sslContect
方法,如
//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。
HttpURLConnection class from java.net package can be used to send Java HTTP Request programmatically. Today we will learn how to use HttpURLConnection in java program to send GET and POST requests and then print the response.
以下是使用 HttpURLConnection class.[=15= 发送 Java HTTP 请求需要遵循的步骤]
- 从 GET/POST URL 字符串创建 URL object。
- 在 URL object 的 returns 实例上调用 openConnection() 方法 HttpURL连接
- 在HttpURLConnection实例中设置请求方式,默认 值为 GET。
- 在 HttpURLConnection 实例上调用 setRequestProperty() 方法 设置请求 header 值,例如“User-Agent”和 “Accept-Language”等
- 我们可以调用getResponseCode()来获取响应HTTP代码。 这样我们就知道请求是否被成功处理或在那里 是否抛出任何 HTTP 错误消息。
- 对于GET,我们可以简单地使用Reader和InputStream来读取 响应并进行相应处理。
- 对于POST,在我们读取响应之前我们需要获取OutputStream 来自 HttpURLConnection 实例并将 POST 参数写入 它。
HttpURLConnection Example
基于上述步骤,下面的示例程序显示了 HttpURLConnection 发送 Java GET 和 POST 的用法请求。
JAVA CODE
package com.mr.rockerz.HttpUrlExample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionExample {
private static final String USER_AGENT = "Mozilla/5.0";
private static final String GET_URL = "https://localhost:9090/SpringMVCExample";
private static final String POST_URL = "https://localhost:9090/SpringMVCExample/home";
private static final String POST_PARAMS = "userName=Pankaj";
public static void main(String[] args) throws IOException {
sendGET();
System.out.println("GET DONE");
sendPOST();
System.out.println("POST DONE");
}
private static void sendGET() throws IOException {
URL obj = new URL(GET_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("GET request not worked");
}
}
private static void sendPOST() throws IOException {
URL obj = new URL(POST_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST request not worked");
}
}
}
当我们执行上面的程序时,我们得到以下响应。
GET Response Code :: 200
<html><head> <title>Home</title></head><body><h1> Hello world! </h1><P> The time on the server is March 6, 2015 9:31:04 PM IST. </P></body></html>
GET DONE
POST Response Code :: 200
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>User Home Page</title></head><body><h3>Hi Pankaj</h3></body></html>
POST DONE
如果您有任何疑问,请在评论中提问。