简体   繁体   中英

Servlet request to another servlet with authorization

I have tomcat server with some applications. This server uses standart j_secure_check auth. On another tomcat server I need to deploy application that must be some proxy to first server. So I need to invoke servlet from another servlet but first I need to do authentication with j_secure_check. Is it possible to do it programmely?

You need to grab the session cookie and pass it through on subsequent requests.

String url = "http://example.com/j_security_check?j_username=foo&j_password=bar";
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();

if (connection.getResponseCode() == 200) { // 200 = OK, 401 = unauthorized
    String cookie = connection.getHeaderField("Set-Cookie").split(";", 2)[0];

    url = "http://example.com/somepage.jsp";
    connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestProperty("Cookie", cookie);
    InputStream input = connection.getInputStream();
    // You can now write it to response.getOutputStream().
}

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