瀏覽器彈出的「Windows安全性」對話框實為**HTTP Basic Authentication**。Java程序訪問此類頁面,需在請求頭中添加`Authorization: Basic
import java.io.*;
import java.net.*;
import java.util.Base64; // Java 8+
public class BasicAuthClient {
public static String getContent(String urlStr, String username, String password) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 1. 構建 Basic Auth Header
String auth = username + ":" + password;
String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
conn.setRequestProperty("Authorization", "Basic " + encodedAuth);
// 2. 設置通用請求屬性
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(10000);
conn.setRequestProperty("User-Agent", "Java BasicAuth Client");
// 3. 處理響應
int responseCode = conn.getResponseCode();
InputStream is = (responseCode >= 200 && responseCode < 300) ?
conn.getInputStream() : conn.getErrorStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) sb.append(line).append('\n');
return sb.toString();
}
}
public static void main(String[] args) throws IOException {
String content = getContent("https://192.168.1.100/protected", "admin", "password123");
System.out.println(content);
}
}
org.apache.httpcomponents
httpclient
4.5.14
import org.apache.http.auth.*;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.*;
import org.apache.http.impl.auth.*;
import org.apache.http.util.EntityUtils;
public class HttpClientBasicAuth {
public static String getContent(String url, String user, String pass) throws Exception {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
new UsernamePasswordCredentials(user, pass)
);
try (CloseableHttpClient httpClient = HttpClientBuilder.create()
.setDefaultCredentialsProvider(credsProvider)
.setDefaultAuthSchemeRegistry(new RegistryBuilder()
.register(AuthSchemes.BASIC, new BasicSchemeFactory())
.build())
.build()) {
HttpGet request = new HttpGet(url);
try (CloseableHttpResponse response = httpClient.execute(request)) {
return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
}
}
}
}
| 場景 | 處理方式 |
|---|---|
| NTLM/Kerberos認證 | HttpClient配置`NTCredentials`/`KerberosCredentials`,需域環境支持 |
| 重定向攜帶認證 | HttpClient默認處理;HttpURLConnection需手動跟隨重定向並重新設置Header |
| 代理服務器認證 | 設置`Proxy` + `CredentialsProvider` for proxy scope |
| 雙向SSL + Basic Auth | 配置`SSLContext`客戶端證書 + Basic Auth Header |
Windows身份驗證彈窗 = HTTP Basic Auth,Java只需在請求頭加入Base64編碼的用戶名密碼即可訪問。