简体   繁体   中英

HttpURLConnection - How to send Headers in setRequestProperty

I am trying to send headers in the given URL using Java code like below:

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

Then in my application I am checking that Auth-Token like below:

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

When I call the above URL in post man with headers then it works fine. But when I run the URL in Java code then SecurityContextHolder.getContext().getAuthentication() always returns null .

What am I doing wrong?

Adding the following line before creating the URL fixed my problem:

CookieHandler.setDefault(new CookieManager());

Sending headers in the given URL now looks like this and it works:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM