使用基本认证发送 HTTP 请求

Java:
使用基本认证发送 HTTP 请求

如何:

import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;

public class BasicAuthExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://example.com/api/data");
            Authenticator.setDefault(new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("username", "password".toCharArray());
                }
            });

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            int status = connection.getResponseCode();
            System.out.println("Response Code: " + status);

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }

            in.close();
            System.out.println("Response Body: " + content);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

输出样例:

Response Code: 200
Response Body: { "data": "This is the data from the server." }

深潜

发送带有基本认证的HTTP请求一直是一个老生常谈的话题。它的历史可追溯到早期的HTTP协议。虽然现今有更安全的认证方式(如OAuth 2.0),但因为简便性,基本认证仍广泛用于内网和不那么敏感的数据访问。重要的实现细节包括在请求头中包含一个经过Base64编码的用户名和密码组合,并以Authorization: Basic来加以前缀。

参见