java a simple way to get Header and Body requested by http
- 2020-05-16 06:55:20
- OfStack
In the http request, there are Header and Body, read header using request.getHeader ("...") );
Body is read using request.getReader (), but getReader gets BufferedReader and needs to be converted to a string. Here's how.
public class TestController {
@RequestMapping("/a")
protected void doPost(HttpServletRequest request,
HttpServletResponse response, BufferedReader br)
throws ServletException, IOException {
//Header Part of the
System.out.print(request.getHeaderNames());
Enumeration<?> enum1 = request.getHeaderNames();
while (enum1.hasMoreElements()) {
String key = (String) enum1.nextElement();
String value = request.getHeader(key);
System.out.println(key + "\t" + value);
}
//body Part of the
String inputLine;
String str = "";
try {
while ((inputLine = br.readLine()) != null) {
str += inputLine;
}
br.close();
} catch (IOException e) {
System.out.println("IOException: " + e);
}
System.out.println("str:" + str);
}