只有POST請求方式,才有請求體,在請求體中封裝了POST請求的請求參數(shù)。
1、getReader()方法用于獲取HTTP請求體的字符流,可以用于讀取HTTP請求體的文本數(shù)據(jù)。getReader()方法返回BufferedReader對象,該對象提供了readLine()方法和read()方法,可以用于逐行或逐個字符地讀取HTTP請求體的文本數(shù)據(jù)。
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.BufferedReader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {
@RequestMapping("/myurl")
public void myMethod(HttpServletRequest request) throws IOException {
BufferedReader reader = request.getReader();
String line = null;
while ((line = reader.readLine()) != null) {
// 處理讀取到的數(shù)據(jù)
}
// TODO: 處理HTTP請求的業(yè)務邏輯
}
}
在這個示例中,我們首先使用request.getReader()方法獲取BufferedReader對象,然后使用while循環(huán)從對象中逐行讀取數(shù)據(jù)。需要注意的是,輸入流中的數(shù)據(jù)格式由HTTP請求頭中的Content-Type字段決定。
另外需要注意的是,當使用getReader()方法獲取HTTP請求體的字符流時,就不能再使用getInputStream()方法獲取HTTP請求體的輸入流了,否則會拋出IllegalStateException異常。原因是,HTTP請求體的數(shù)據(jù)只能被讀取一次,如果已經被讀取過了,就無法再次讀取。文章來源:http://www.zghlxwxcb.cn/news/detail-730055.html
2、getInputStream()方法用于獲取HTTP請求體的輸入流,可以用于讀取HTTP請求體的二進制數(shù)據(jù)。getInputStream()方法返回ServletInputStream對象,該對象提供了read(byte[] b, int off, int len)方法和read()方法,可以用于從輸入流中讀取HTTP請求體的二進制數(shù)據(jù)。
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import javax.servlet.ServletInputStream;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {
@RequestMapping("/myurl")
public void myMethod(HttpServletRequest request) throws IOException {
ServletInputStream inputStream = request.getInputStream();
byte[] buffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
// 處理讀取到的數(shù)據(jù)
}
// TODO: 處理HTTP請求的業(yè)務邏輯
}
}
使用request.getInputStream()方法獲取ServletInputStream對象,然后使用while循環(huán)從對象中讀取數(shù)據(jù)。文章來源地址http://www.zghlxwxcb.cn/news/detail-730055.html
到了這里,關于07-HTTP-Request獲取請求體數(shù)據(jù)方法getReader()\getInputStream()的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!