概念: Hyper Text Transfer Protocol 超文本傳輸協議,規定了瀏覽器和服務器之間的數據傳輸規則
特點
- 基于TCP協議,面向連接,安全
- 基于請求-響應模型的,一次請求對應一次響應
- 無狀態的,對于事物沒有記憶能力,每次請求-響應都是獨立的
-
- 缺點:多次請求間不能共享數據
-
- 優點: 響應速度快
請求協議
常見請求字段
- Get方式:請求參數在請求行中,沒有請求體,請求大小在瀏覽器中是有限制的。
- Post方式:請求參數在請求體中,請求大小沒有限制。
請求數據獲取
- web服務器(Tomcat)對http協議的請求數據進行了解析,并進行了封裝(HttpServeletRequest),在調用controller方法的時候自動傳遞給了該方法,因此我們不必直接對原始協議進行操作。
代碼示例:
package com.huohuo;import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class RequestController {@RequestMapping(value = "/request")public String request(HttpServletRequest request) {// 獲取請求方式String method = request.getMethod();// 獲取請求路徑String requestURL = request.getRequestURL().toString();String requestURI = request.getRequestURI(); // 是資源訪問路徑// 獲取請求協議String protocol = request.getProtocol();// 獲取請求參數 - name, ageString name = request.getParameter("name");String age = request.getParameter("age");// 獲取請求頭 - AcceptString accept = request.getHeader("Accept");return "OK<br/>" +"method:" + method + "<br/>" +"requestURL:" + requestURL + "<br/>" +"requestURI:" + requestURI + "<br/>" +"protocol:" + protocol + "<br/>" +"name:" + name + "<br/>" +"age:" + age + "<br/>" +"accept:" + accept + "<br/>";}
}
啟動后訪問localhost:8080/request?name=huohuo&age=18
響應協議
以下是常見的響應狀態碼:
web服務器對http協議的響應數據進行了封裝(HttpServeletResponse),并在調用Controller方法的時候傳遞了該方法,這就使得程序員不必對協議直接進行操作,讓web開發更加便捷。
使用response或spring對象進行響應
@RequestMapping("/response")// 第一種方式,響應體是字符串,會自動設置響應頭 Content-Type: text/plain;charset=UTF-8public void Response(HttpServletResponse response) throws IOException {// 設置響應狀態碼response.setStatus(HttpServletResponse.SC_OK); // 200// 設置響應頭response.setHeader("name", "huohuo");// 設置響應體// 會拋出 IOException, 因為 response.getWriter() 獲取的流,是和 response 關聯的,response.getWriter().write("<h1> hello response </h1>");}
// 使用spring中提供的方式,封裝對象返回
@RequestMapping("/response2")
// 這是第二種方式,返回 ResponseEntity 對象,會自動設置響應頭 Content-Type: text/plain;charset=UTF-8,也可以手動設置
public ResponseEntity<String> response2(HttpServletRequest request) {return ResponseEntity.status(200).header("name2", "huohuo2").body("<h1> hello response2 </h1>");
}
注:響應頭和響應狀態碼如果沒有特殊要求的話,通常不手動設定,服務器會根據請求處理的邏輯自動設置狀態碼和頭
完
致謝:本文參考黑馬程序員的視頻。
https://www.bilibili.com/video/BV1yGydYEE3H/?vd_source=1b8f9bfb1d0891faf1c70d7678ae56db