介紹
從java.net
包中的HttpURLConnection
類可以用於以編程方式發送Java HTTP請求。在本文中,您將學習如何在Java程序中使用HttpURLConnection
來發送GET
和POST
請求,然後打印響應。
先決條件
對於這個HttpURLConnection
示例,您應該已經完成了Spring MVC教程,因為它有GET
和POST
HTTP方法的URL。
考慮部署到localhost
Tomcat服務器。
SpringMVCExample 摘要
Java HTTP GET 請求
localhost:8080/SpringMVCExample/
Java HTTP GET 請求登錄頁面
localhost:8080/SpringMVCExample/login
Java HTTP POST 請求
localhost:8080/SpringMVCExample?userName=Pankaj
localhost:8080/SpringMVCExample/login?userName=Pankaj&pwd=apple123
– 用於多個參數
從表單中獲取參數
登錄頁面的HTML包含以下表單:
<!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>Login Page</title>
</head>
<body>
<form action="home" method="post">
<input type="text" name="userName"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
-
method
為POST
。 -
action
為home
。localhost:8080/SpringMVCExample/home
userName
的類型為text
。
您可以構建一個 POST
請求到:
localhost:8080/SpringMVCExample/home?userName=Pankaj
這將作為 HttpURLConnection
示例的基礎。
HttpURLConnection
示例
以下是使用 HttpURLConnection
類發送Java HTTP請求的步驟:
- 從
GET
或POST
URL 字符串創建一個URL
對象。 - 調用 URL 對象上的
openConnection()
方法,該方法返回HttpURLConnection
的一個實例。 - 在
HttpURLConnection
實例中設置請求方法(預設值為GET
)。 - 呼叫
HttpURLConnection
實例上的setRequestProperty()
方法以設置請求標頭值(例如"User-Agent"
、"Accept-Language"
等)。 - 我們可以呼叫
getResponseCode()
來獲取回應的 HTTP 狀態碼。這樣,我們就知道請求是否成功處理,或者是否有任何 HTTP 錯誤消息被拋出。 - 對於
GET
,使用Reader
和InputStream
讀取回應並相應地處理它。 - 對於
POST
,在代碼處理回應之前,它需要從HttpURLConnection
實例獲取OutputStream
,並將POST
參數寫入其中。
這裡是一個使用 HttpURLConnection
發送 Java GET
和 POST
請求的範例程序:
HttpURLConnectionExample.java
package com.journaldev.utils;
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) { // 成功
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 輸出結果
System.out.println(response.toString());
} else {
System.out.println("GET request did not work.");
}
}
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);
// 僅適用於 POST - 開始
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// 僅適用於 POST - 結束
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // 成功
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 輸出結果
System.out.println(response.toString());
} else {
System.out.println("POST request did not work.");
}
}
}
編譯並運行該代碼。它將產生以下輸出:
OutputGET 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
將此輸出與瀏覽器的 HTTP 響應進行比較。
如果您需要通過 HTTPS 協議發送 GET
和 POST
請求,那麼您需要使用 javax.net.ssl.HttpsURLConnection
而不是 java.net.HttpURLConnection
。 HttpsURLConnection
將處理 SSL 握手和加密。
結論
在本文中,您學會了如何在 Java 程式中使用 HttpURLConnection
發送 GET
和 POST
請求,然後打印響應。
繼續學習更多 Java 教程。