java获取http请求的Header和Body

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

 

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

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)