在 Java Web 開發中,無論是發送 HTTP 請求還是在 Servlet 中接收參數,正確處理 URL 參數都是基礎且關鍵的技能。本文將系統講解如何使用原生 Java 代碼實現 GET/POST 請求發送,以及在 Servlet 容器中獲取完整的請求 URL 與參數列表。
Java 標準庫提供的 HttpURLConnection 是最基礎的 HTTP 客戶端工具,無需引入第三方依賴即可完成請求發送與響應讀取。
public static String sendGet(String url, String param) {
StringBuilder result = new StringBuilder();
try {
// 拼接完整 URL:基礎路徑 + ? + 參數字符串
String urlName = url + "?" + param;
URL realUrl = new URL(urlName);
URLConnection connection = realUrl.openConnection();
// 建立連接
connection.connect();
// 讀取響應流
try (BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
}
} catch (Exception e) {
System.err.println("GET 請求異常:" + e.getMessage());
e.printStackTrace();
}
return result.toString();
}
關鍵點說明:
key1=value1&key2=value2 格式編碼(建議使用 URLEncoder.encode 處理中文)public static String sendPost(String url, String param) {
StringBuilder result = new StringBuilder();
try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
// 必須設置輸入輸出
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Charset", "UTF-8");
// 寫入請求體
try (PrintWriter out = new PrintWriter(
new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8))) {
out.print(param);
out.flush();
}
// 讀取響應
try (BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
}
} catch (Exception e) {
System.err.println("POST 請求異常:" + e.getMessage());
e.printStackTrace();
}
return result.toString();
}
POST 請求注意事項:
setDoOutput(true) 才能寫入請求體flush() 確保數據發送在 Servlet 環境下,HttpServletRequest 提供了豐富的 API 來獲取請求信息,但 GET 與 POST 參數獲取方式略有不同。
| 需求 | GET 請求 | POST 請求 | 通用方案 |
|---|---|---|---|
| 完整請求 URL | getRequestURL() | getRequestURL() | getRequestURL() |
| 查詢字符串 | getQueryString() | 無(參數在請求體) | 需手動拼接 |
| 所有參數 Map | getParameterMap() | getParameterMap() | getParameterMap() |
@WebServlet("/param-demo")
public class RequestParamServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
printRequestInfo(req, "GET");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
printRequestInfo(req, "POST");
}
private void printRequestInfo(HttpServletRequest request, String method)
throws IOException {
request.setCharacterEncoding("UTF-8");
resp.setContentType("text/plain;charset=UTF-8");
PrintWriter writer = resp.getWriter();
// 1. 獲取完整 URL(不含參數)
StringBuilder fullUrl = new StringBuilder(request.getRequestURL().toString());
// 2. 獲取所有參數並拼接
Map paramMap = request.getParameterMap();
StringBuilder queryString = new StringBuilder();
for (Map.Entry entry : paramMap.entrySet()) {
String key = entry.getKey();
for (String value : entry.getValue()) {
queryString.append(key).append('=').append(value).append('&');
}
}
// 移除末尾 &
if (queryString.length() > 0) {
queryString.setLength(queryString.length() - 1);
}
// 3. 輸出結果
writer.println(method + " 請求完整路徑: " + fullUrl);
writer.println(method + " 請求參數列表: " + queryString);
// 4. 如果是 GET,還可直接獲取原始查詢字符串
if ("GET".equals(method)) {
writer.println("原始 QueryString: " + request.getQueryString());
}
}
}
URLEncoder.encode(value, "UTF-8")雖然原生 API 學習價值高,但生產環境建議使用成熟的 HTTP 客戶端庫:
掌握底層原理有助於排查疑難雜症,實際開發中選擇合適的工具才能事半功倍。