共計(jì) 876 個(gè)字符,預(yù)計(jì)需要花費(fèi) 3 分鐘才能閱讀完成。
在 Java 中,可以使用 Servlet 或 Spring 框架來獲取 POST 請(qǐng)求的請(qǐng)求體。
- 使用 Servlet:
- 在 Servlet 中重寫 doPost 方法,通過 HttpServletRequest 對(duì)象的 getInputStream 方法獲取請(qǐng)求體的輸入流。
- 使用 IO 流的方式讀取輸入流中的數(shù)據(jù)。
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {BufferedReader reader = req.getReader();
StringBuilder requestBody = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {requestBody.append(line);
}
// requestBody.toString() 即為請(qǐng)求體內(nèi)容}
- 使用 Spring 框架:
- 在 Controller 的方法參數(shù)中使用 @RequestBody 注解來接收請(qǐng)求體的內(nèi)容。
@PostMapping("/api")
public String handlePostRequest(@RequestBody String requestBody) {// requestBody 即為請(qǐng)求體內(nèi)容}
或者,使用對(duì)象來接收請(qǐng)求體的內(nèi)容。
public class RequestBodyDto {
private String param1;
private int param2;
// getters and setters
}
@PostMapping("/api")
public String handlePostRequest(@RequestBody RequestBodyDto requestBodyDto) {// requestBodyDto 即為請(qǐng)求體內(nèi)容的映射對(duì)象}
以上是兩種常見的獲取 POST 請(qǐng)求的請(qǐng)求體的方法。根據(jù)具體的應(yīng)用場(chǎng)景和框架選擇適合自己的方式。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完
發(fā)表至: Java
2023-12-20