Java 怎么在servlet中获取请求头(Request Header)

2019年8月16日22:05:59 评论 26

1.简介

Java 怎么在servlet中获取请求头(Request Header)?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    doGetOrPost(req, resp);
}

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    doGetOrPost(req, resp);
}

private void doGetOrPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    PrintWriter out = resp.getWriter();
    resp.setContentType("text/plain");

    
    String name = "user-agent";
    String value = req.getHeader(name);
    if (value == null) {
        
    }
    
    Enumeration enum = req.getHeaderNames();
    for (; enum.hasMoreElements(); ) {
        
        name = (String)enum.nextElement();
        out.println(name);

        
        value = req.getHeader(name);

        Enumeration valuesEnum = req.getHeaders(name);
        for (; valuesEnum.hasMoreElements(); ) {
            
            value = (String)valuesEnum.nextElement();

            out.println("    "+value);
        }
    }
    out.close();
}

 

3.总结

示例代码演示了 Java 怎么在servlet中获取请求头(Request Header),具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: