• Home
  • LLMs
  • Docker
  • Kubernetes
  • Java
  • All
  • About
Samples | Cookie-based Authentication (Java Client Example)
  1. Notes
  2. Maven POM file (dependencies)
  3. Java Client Example (WebTarget)
  4. Java Client Example (WebTarget/ClientRequestFilter)
  5. Java Client Example (URLConnection)

  1. Notes
    See this page for details how to configure FORM Authentication with Apache Tomcat:
    FORM Authentication with Apache Tomcat
  2. Maven POM file (dependencies)
    <dependencies>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.1.1</version>
        </dependency>
    
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-common</artifactId>
            <version>2.29.1</version>
        </dependency>
    
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-client</artifactId>
            <version>2.29.1</version>
        </dependency>
    
        <dependency>
            <groupId>org.glassfish.jersey.inject</groupId>
            <artifactId>jersey-hk2</artifactId>
            <version>2.29.1</version>
        </dependency>
    </dependencies>
  3. Java Client Example (WebTarget)
    import java.io.IOException;
    
    import javax.ws.rs.client.Client;
    import javax.ws.rs.client.ClientBuilder;
    import javax.ws.rs.client.Invocation;
    import javax.ws.rs.client.WebTarget;
    import javax.ws.rs.core.Cookie;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    
    import org.glassfish.jersey.logging.LoggingFeature;
    
    public class Test {
        public static void main(String[] args) throws IOException {
            final String url = "http://localhost:8080/auth/jsp/";
    
            final String cookieName = "JSESSIONID";
            final String cookieValue = "C4AB71C3C27DEFF400FBEE8974CCB4D9";
    
            Cookie cookie = new Cookie(cookieName, cookieValue);
    
            final Client client = ClientBuilder.newBuilder()
                    .property(LoggingFeature.LOGGING_FEATURE_VERBOSITY_CLIENT, LoggingFeature.Verbosity.PAYLOAD_ANY)
                    .property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_CLIENT, "INFO").build();
    
            WebTarget webTarget = client.target(url);
    
            Invocation.Builder invocationBuilder = webTarget.request(MediaType.TEXT_HTML);
    
            invocationBuilder = invocationBuilder.cookie(cookie);
    
            Response response = invocationBuilder.get();
    
            //System.out.println(response.getStatus());
    
            //System.out.println(response.readEntity(String.class));
        }
    }

    Output:
    Oct 13, 2015 1:40:47 PM org.glassfish.jersey.logging.LoggingInterceptor log
    INFO: 1 * Sending client request on thread main
    1 > GET http://localhost:8080/auth/jsp/
    1 > Accept: text/html
    1 > Cookie: $Version=1;JSESSIONID=C4AB71C3C27DEFF400FBEE8974CCB4D9
    
    Oct 13, 2015 1:40:47 PM org.glassfish.jersey.logging.LoggingInterceptor log
    INFO: 1 * Client response received on thread main
    1 < 200
    1 < Cache-Control: private
    1 < Content-Length: 99
    1 < Content-Type: text/html;charset=ISO-8859-1
    1 < Date: Sun, 13 Oct 2015 17:40:47 GMT
    1 < Expires: Wed, 31 Dec 1969 19:00:00 EST
    <html>
      <body>
    User: tomcat
      </body>
    </html>
  4. Java Client Example (WebTarget/ClientRequestFilter)
    import java.io.IOException;
    
    import javax.ws.rs.client.Client;
    import javax.ws.rs.client.ClientBuilder;
    import javax.ws.rs.client.ClientRequestContext;
    import javax.ws.rs.client.ClientRequestFilter;
    import javax.ws.rs.client.Invocation;
    import javax.ws.rs.client.WebTarget;
    import javax.ws.rs.core.HttpHeaders;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    
    import org.glassfish.jersey.logging.LoggingFeature;
    
    public class Test {
        public static void main(String[] args) throws IOException {
            final String url = "http://localhost:8080/auth/jsp/";
    
            final String cookieName = "JSESSIONID";
            final String cookieValue = "8CDAA8F9254720AABDB920F899AD0768";
    
            final Client client = ClientBuilder.newBuilder()
                    .property(LoggingFeature.LOGGING_FEATURE_VERBOSITY_CLIENT, LoggingFeature.Verbosity.PAYLOAD_ANY)
                    .property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_CLIENT, "INFO").build();
    
            WebTarget webTarget = client.target(url);
    
            webTarget.register(new CookieClientRequestFilter(cookieName, cookieValue));
    
            Invocation.Builder invocationBuilder = webTarget.request(MediaType.TEXT_HTML);
    
            Response response = invocationBuilder.get();
    
            //System.out.println(response.getStatus());
    
            //System.out.println(response.readEntity(String.class));
        }
    }
    
    class CookieClientRequestFilter implements ClientRequestFilter {
        private final String cookieName;
    
        private final String cookieValue;
    
        public CookieClientRequestFilter(final String cookieName, final String cookieValue) {
            this.cookieName = cookieName;
            this.cookieValue = cookieValue;
        }
    
        @Override
        public void filter(final ClientRequestContext requestContext) throws IOException {
            requestContext.getHeaders().add(HttpHeaders.COOKIE, cookieName + "=" + cookieValue);
        }
    }

    Output:
    Oct 13, 2015 6:20:31 PM org.glassfish.jersey.logging.LoggingInterceptor log
    INFO: 1 * Sending client request on thread main
    1 > GET http://localhost:8080/auth/jsp/
    1 > Accept: text/html
    1 > Cookie: JSESSIONID=8CDAA8F9254720AABDB920F899AD0768
    
    Oct 13, 2015 6:20:31 PM org.glassfish.jersey.logging.LoggingInterceptor log
    INFO: 1 * Client response received on thread main
    1 < 200
    1 < Cache-Control: private
    1 < Content-Length: 99
    1 < Content-Type: text/html;charset=ISO-8859-1
    1 < Date: Sun, 13 Oct 2015 22:20:31 GMT
    1 < Expires: Wed, 31 Dec 1969 19:00:00 EST
    <html>
      <head>
        <title>Index Page</title>
      </head>
    
      <body>
    User: <b>tomcat
      </body>
    </html>
  5. Java Client Example (URLConnection)
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.List;
    import java.util.Map;
    
    import javax.ws.rs.core.HttpHeaders;
    import javax.ws.rs.core.MediaType;
    
    public class Test {
        public static void main(String[] args) throws IOException {
            final String targetURL = "http://localhost:8080/auth/jsp/";
    
            final String cookieName = "JSESSIONID";
            final String cookieValue = "C4AB71C3C27DEFF400FBEE8974CCB4D9";
    
            HttpURLConnection connection = null;
            try {
                final URL url = new URL(targetURL);
    
                connection = (HttpURLConnection) url.openConnection();
    
                connection.setRequestMethod("GET");
    
                final String cookie = cookieName + "=" + cookieValue;
    
                connection.setRequestProperty(HttpHeaders.COOKIE, cookie);
                connection.setRequestProperty("Accept", MediaType.TEXT_HTML);
    
                // response code
                System.out.println(connection.getResponseCode());
    
                // response headers
                final Map<String, List<String>> headerFields = connection.getHeaderFields();
                for (final Map.Entry<String, List<String>> entry : headerFields.entrySet()) {
                    System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
                }
    
                // response body
                if (connection.getInputStream() != null) {
                    final StringBuilder response = new StringBuilder();
                    try (final InputStream inputStream = connection.getInputStream();
                            final InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                            final BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
                        String line;
                        while ((line = bufferedReader.readLine()) != null) {
                            response.append(line);
                            response.append('\n');
                        }
                    }
                    System.out.println(response.toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }
    }

    Output:
    200
    Key: null, Value: [HTTP/1.1 200]
    Key: Cache-Control, Value: [private]
    Key: Expires, Value: [Wed, 31 Dec 1969 19:00:00 EST]
    Key: Content-Length, Value: [99]
    Key: Date, Value: [Sun, 13 Oct 2015 18:57:31 GMT]
    Key: Content-Type, Value: [text/html;charset=ISO-8859-1]
    <html>
      <body>
    User: tomcat
      </body>
    </html>
© 2025  mtitek