对Java中任意URL的HTTP(S)请求



我需要向用户提供的URL(可以是http或https)发出GET请求

在JavaScript中,我可以这样做:

fetch(prompt()).then(r => r.text()).then(console.log)

Java的等效代码是什么?

如何使用自定义证书?

URL/URLConnection

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语句在资源不再使用时自动关闭资源。

这样做很重要,这样你就不会有资源泄漏。

自签名/自定义证书

如本回答中所述,您可以配置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,如下所述。

这更类似于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方法,如下所示:

//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类来自java.net包裹可以用来发送Java HTTP请求编程。今天我们将学习如何使用HttpURLConnection发送GET文章请求,然后打印响应。

下面是使用HttpURLConnection发送Java HTTP请求需要遵循的步骤类。
  1. 创建URL对象从GET/POST URL字符串。
  2. 在URL对象上调用openConnection()方法,返回的实例HttpURLConnection
  3. HttpURLConnection中设置请求方法实例中,默认值为GET。
  4. HttpURLConnection上调用setRequestProperty()方法实例设置请求头值,如"User-Agent"one_answers"接收语言"等。
  5. 我们可以调用getResponseCode()获取响应HTTP代码。这样我们就知道请求是否被成功处理了是否抛出任何HTTP错误消息。对于GET,我们可以简单地使用Reader和InputStream来读取响应并进行相应处理。对于POST,在读取响应之前,我们需要获取OutputStream从HttpURLConnection实例并将POST参数写入它。

HttpURLConnection示例

基于上述步骤,下面是显示HttpURLConnection用法的示例程序发送Java GET和POST请求。

JAVA代码

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

如果你有任何疑问,请在评论中提问。

最新更新