java获取http请求的Header和Body的简单方法

时间:2021-09-26 10:04:15

http请求中,有HeaderBody之分,读取header使用request.getHeader("...");

读取Body使用request.getReader(),但getReader获取的是BufferedReader,需要把它转换成字符串,下面是转换的方法。

java" id="highlighter_760552">
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class TestController {
 
  @RequestMapping("/a")
  protected void doPost(HttpServletRequest request,
      HttpServletResponse response, BufferedReader br)
      throws ServletException, IOException {
//Header部分
    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部分
    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);
  }

以上就是小编为大家带来的java获取http请求的Header和Body的简单方法全部内容了,希望大家多多支持服务器之家~