• Home
  • LLMs
  • Docker
  • Kubernetes
  • Java
  • All
  • About
Samples | BASIC Authentication (Java Client Example)
  1. Notes
  2. Maven POM file (dependencies)
  3. Java Client Example (WebTarget)
  4. Java Client Example (URLConnection)

  1. Notes
    See this page for details how to configure BASIC Authentication with Apache Tomcat:
    BASIC 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 java.util.Map;
    
    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.MediaType;
    import javax.ws.rs.core.NewCookie;
    import javax.ws.rs.core.Response;
    
    import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
    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 username = "tomcat";
            final String password = "tomcat";
    
            final Client client = ClientBuilder.newBuilder()
                    .property(LoggingFeature.LOGGING_FEATURE_VERBOSITY_CLIENT, LoggingFeature.Verbosity.PAYLOAD_ANY)
                    .property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_CLIENT, "INFO").build();
    
            final WebTarget webTarget = client.target(url);
    
            final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder().build();
    
            webTarget.register(feature);
    
            final Invocation.Builder invocationBuilder = webTarget.request(MediaType.TEXT_HTML);
    
            invocationBuilder.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_BASIC_USERNAME, username);
            invocationBuilder.property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_BASIC_PASSWORD, password);
    
            final Response response = invocationBuilder.get();
    
            // response status
            //System.out.println(response.getStatus());
    
            // response cookies
            //for (final Map.Entry<String, NewCookie> entry : response.getCookies().entrySet()) {
            //    System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
            //}
    
            // response body
            //System.out.println(response.readEntity(String.class));
        }
    }

    Output:
    Oct 13, 2015 1:03:27 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 > Authorization: Basic dG9tY2F0OjEyMzQ1Ng==
    
    Oct 13, 2015 1:03:27 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:03:27 GMT
    1 < Expires: Wed, 31 Dec 1969 19:00:00 EST
    1 < Set-Cookie: JSESSIONID=A4A610655B767AFE929F1240AB3A8F0B;path=/auth;HttpOnly
    <html>
      <body>
    User: tomcat
      </body>
    </html>
  4. Java Client Example (URLConnection)
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.Base64;
    import java.util.List;
    import java.util.Map;
    
    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 int connectTimeout = 30000;
    
            final String username = "tomcat";
            final String password = "tomcat";
    
            final String username_password = username + ":" + password;
            final String encoded_username_password = Base64.getEncoder().encodeToString(username_password.getBytes());
    
            final URL url = new URL(targetURL);
    
            final URLConnection connection = url.openConnection();
            connection.setConnectTimeout(connectTimeout);
            connection.setRequestProperty("Authorization", "Basic " + encoded_username_password);
            connection.setRequestProperty("Accept", MediaType.TEXT_HTML);
    
            // 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 StringBuffer response = new StringBuffer();
                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());
            }
        }
    }

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