调用第三方接口进行Basic认证

import java.io.IOException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.HttpURLConnection;

public class Main {
    public static void main(String[] args) throws IOException {
        String url = "https://api.example.com/endpoint";
        String username = "your-username";
        String password = "your-password";

        EsbAuth esbAuth = new EsbAuth(username, password);
        Authenticator.setDefault(esbAuth);

        URL apiUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();

        // 发送请求并处理响应
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 处理成功响应
        } else {
            // 处理失败响应
        }

        connection.disconnect();
    }

    static class EsbAuth extends Authenticator {
        private final String username;
        private final String password;

        public EsbAuth(String username, String password) {
            this.username = username;
            this.password = password;
        }

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password.toCharArray());
        }
    }
}

在这个示例中,我们创建了一个 EsbAuth 类作为 Authenticator 的子类,并在构造函数中接收账号和密码。在 getPasswordAuthentication 方法中,我们返回一个 PasswordAuthentication 对象,该对象包含了账号和密码。

在 main 方法中,我们创建了一个 EsbAuth 实例,并通过 Authenticator.setDefault() 方法将其设置为默认的 Authenticator。然后,我们打开一个 HttpURLConnection 并发送请求。

您需要将 url 替换为要调用的实际接口地址,并将 username 和 password 替换为相应的凭据。

通过这种方式,您可以使用自定义的 EsbAuth 类进行基本认证,并将其设置为默认的 Authenticator,以在发送请求时自动添加基本认证标头。请注意,Authenticator 是 Java 标准库中的类,不依赖于任何特定的 HTTP 客户端库。

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值