天天看点

java获取http请求的Header和Body

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

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);
    }