HttpURLConnection - 如何在setRequestProperty中发送标头

时间:2016-01-20 12:38:55

标签: java httpurlconnection

我正在尝试使用以下Java代码在给定的URL中发送标头:

URL u = new URL("http://domain:8081/App/mycall");
HttpURLConnection con= (HttpURLConnection) u.openConnection();
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Auth-Token", authToken);
BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));

然后在我的应用程序中,我正在检查Auth-Token,如下所示:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    if (SecurityContextHolder.getContext().getAuthentication() != null) {
        String reqToken = req.getHeader("Auth-Token");
    }
}

当我在带有标题的post man中调用上述URL时,它可以正常工作。但是当我在Java代码中运行URL时,SecurityContextHolder.getContext().getAuthentication()总是返回null

我做错了什么?

1 个答案:

答案 0 :(得分:-1)

在创建URL之前添加以下行修复了我的问题:

CookieHandler.setDefault(new CookieManager());

现在,在给定网址中发送标题如下所示,它可以正常运行:

CookieHandler.setDefault(new CookieManager());
URL u = new URL("http://domain:8081/App/mycall");
HttpURLConnection con= (HttpURLConnection) u.openConnection();
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Auth-Token", authToken);
BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));