How to Fetch a URL with HTTP Basic Authentication in Java?

Question

How can I fetch a URL using HTTP Basic Authentication in Java?

String url = "http://example.com/api/resource"; URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

String user = "username";
String password = "password";
String encoded = Base64.getEncoder().encodeToString((user + ":" + password).getBytes(StandardCharsets.UTF_8));
con.setRequestProperty("Authorization", "Basic " + encoded);

Answer

Fetching a URL with HTTP Basic Authentication in Java can be accomplished using either the built-in `HttpURLConnection` class or third-party libraries like Apache HttpClient. This process involves encoding your credentials and adding them to the request headers.

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.nio.charset.StandardCharsets;

public class BasicAuthExample {
    public static void main(String[] args) {
        try {
            String url = "http://example.com/api/resource";
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            String user = "username";
            String password = "password";
            String encoded = Base64.getEncoder().encodeToString((user + ":" + password).getBytes(StandardCharsets.UTF_8));
            con.setRequestProperty("Authorization", "Basic " + encoded);

            int responseCode = con.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            // Additional code to read the response... 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Causes

  • Incorrect URL format
  • Invalid credentials
  • Network issues preventing connection
  • Missing required headers in the request

Solutions

  • Ensure the URL is correctly formatted and accessible
  • Double-check username and password for accuracy
  • Check network settings and firewall configurations
  • Include necessary HTTP headers in your request

Common Mistakes

Mistake: Not encoding credentials properly.

Solution: Always use `Base64` encoding to format the username and password correctly before sending.

Mistake: Using an incorrect URL.

Solution: Verify the URL and ensure that it points to a valid endpoint that requires authentication.

Mistake: Neglecting to check HTTP response codes.

Solution: Always check the response code to ensure the request was successful.

Helpers

  • Java HTTP Basic Authentication
  • fetch URL in Java
  • Java HTTP request
  • HttpURLConnection example
  • Apache HttpClient basic auth

Related Questions

⦿How Can You Call a COM API from Java?

Learn how to call a COM API in Java including methods code examples and common mistakes to avoid for successful integration.

⦿How to Resolve the 'Library Not Accessible for Namespace Classloader' Error?

Learn how to fix the library is not accessible for the namespace classloader error in your application with expert tips and solutions.

⦿How to Configure a Socket in Java to Accept Connections Only from localhost

Learn how to set up a Java socket to accept connections exclusively from localhost with code examples and troubleshooting tips.

⦿How to Troubleshoot Issues with @GeneratedValue in H2 Database?

Learn how to resolve issues with GeneratedValue in H2 database including common mistakes and troubleshooting tips.

⦿Can You Use Both Java and Python in Google App Engine Applications?

Explore if you can mix Java and Python code in Google App Engine and learn best practices for multilanguage applications.

⦿How to Implement Multiple Endpoints in a REST API with Spring Boot

Learn how to create multiple endpoints in a RESTful API using Spring Boot with this detailed guide including examples and best practices.

⦿How to Find JConsole in Mac OS X Leopard

Learn where to locate JConsole in Mac OS X Leopard with this detailed guide. Discover tips and troubleshooting techniques.

⦿Why Is It Necessary to Use dispose() on java.awt.Window Instances Going Out of Scope?

Learn why its crucial to call dispose on java.awt.Window instances and manage resources effectively in Java GUI applications.

⦿Step-by-Step Guide to Installing Oracle Java 8 with Ansible

Learn how to automate the installation of Oracle Java 8 using Ansible in this comprehensive guide. Get code snippets and troubleshooting tips.

⦿How to Use JPA POJO as a Data Object in Java Applications

Learn how to correctly utilize JPA POJOs as data objects in your Java applications including best practices and common pitfalls.

© Copyright 2025 - CodingTechRoom.com