java后台通过basic认证

对Basic还不了解的可以参考这篇文章,本文主要是java代码通过basic验证。

该例子使用类Authenticator  来实现。

一、定义类继承Authenticator

import java.net.Authenticator;
import java.net.PasswordAuthentication;

public class MyAuthenticator extends Authenticator {

	private String username;
	private String password;

	public MyAuthenticator(String user, String pwd) {
		this.username = user;
		this.password = pwd;
	}

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

}

二、使用

在你要通过认证的方法中添加如下代码即可

String username = "认证的用户名";
String password = "认证的密码";
Authenticator.setDefault(new MyAuthenticator(username,password));

猜你喜欢

转载自blog.csdn.net/loveLifeLoveCoding/article/details/88051228