如何使用Java HttpURLConnection进行HTTP GET和POST请求

介紹

java.net包中的HttpURLConnection類可以用於以編程方式發送Java HTTP請求。在本文中,您將學習如何在Java程序中使用HttpURLConnection來發送GETPOST請求,然後打印響應。

先決條件

對於這個HttpURLConnection示例,您應該已經完成了Spring MVC教程,因為它有GETPOST 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>
  • methodPOST
  • actionhome
    • localhost:8080/SpringMVCExample/home
  • userName 的類型為 text

您可以構建一個 POST 請求到:

localhost:8080/SpringMVCExample/home?userName=Pankaj

這將作為 HttpURLConnection 示例的基礎。

HttpURLConnection 示例

以下是使用 HttpURLConnection 類發送Java HTTP請求的步驟:

  1. GETPOST URL 字符串創建一個 URL 對象。
  2. 調用 URL 對象上的 openConnection() 方法,該方法返回 HttpURLConnection 的一個實例。
  3. HttpURLConnection 實例中設置請求方法(預設值為 GET)。
  4. 呼叫 HttpURLConnection 實例上的 setRequestProperty() 方法以設置請求標頭值(例如 "User-Agent""Accept-Language" 等)。
  5. 我們可以呼叫 getResponseCode() 來獲取回應的 HTTP 狀態碼。這樣,我們就知道請求是否成功處理,或者是否有任何 HTTP 錯誤消息被拋出。
  6. 對於 GET,使用 ReaderInputStream 讀取回應並相應地處理它。
  7. 對於 POST,在代碼處理回應之前,它需要從 HttpURLConnection 實例獲取 OutputStream,並將 POST 參數寫入其中。

這裡是一個使用 HttpURLConnection 發送 Java GETPOST 請求的範例程序:

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.");
		}
	}

}

編譯並運行該代碼。它將產生以下輸出:

Output
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

將此輸出與瀏覽器的 HTTP 響應進行比較。

如果您需要通過 HTTPS 協議發送 GETPOST 請求,那麼您需要使用 javax.net.ssl.HttpsURLConnection 而不是 java.net.HttpURLConnectionHttpsURLConnection 將處理 SSL 握手和加密。

結論

在本文中,您學會了如何在 Java 程式中使用 HttpURLConnection 發送 GETPOST 請求,然後打印響應。

繼續學習更多 Java 教程

Source:
https://www.digitalocean.com/community/tutorials/java-httpurlconnection-example-java-http-request-get-post