在 Java Maven 项目中实现 URL 鉴权可以通过多种方式来完成,以下将介绍两种常见的实现方式,并提供相应的示例代码和依赖坐标。
基本身份验证是一种通过在 HTTP 请求的头部中添加用户名和密码来进行鉴权的方式。以下是实现步骤:
添加依赖(Maven 和 Gradle):
Maven 依赖坐标:
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>
Gradle 依赖坐标:
implementation 'org.apache.httpcomponents:httpclient:4.5.13'
编写示例代码:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class BasicAuthExample {
    public static void main(String[] args) throws Exception {
        String url = "YOUR_URL_HERE";
        String username = "YOUR_USERNAME";
        String password = "YOUR_PASSWORD";
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
            new AuthScope(AuthScope.ANY),
            new UsernamePasswordCredentials(username, password));
        CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credsProvider)
            .build();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            System.out.println(EntityUtils.toString(entity));
        }
        httpclient.close();
    }
}
这种方式允许你通过在 HTTP 请求的头部中添加自定义的鉴权信息来进行访问控制。以下是实现步骤:
添加依赖(Maven 和 Gradle):无需添加额外依赖。
编写示例代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class CustomAuthExample {
    public static void main(String[] args) throws Exception {
        String urlStr = "YOUR_URL_HERE";
        String username = "YOUR_USERNAME";
        String password = "YOUR_PASSWORD";
        String authString = username + ":" + password;
        String encodedAuthString = Base64.getEncoder().encodeToString(authString.getBytes(StandardCharsets.UTF_8));
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Authorization", "Basic " + encodedAuthString);
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            System.out.println(response.toString());
        } else {
            System.out.println("Request failed with response code: " + responseCode);
        }
    }
}
这些示例代码演示了两种常见的 URL 鉴权方式的实现方法。根据你的需求,选择适合你项目的方式并进行相应的集成。