HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
String encoded = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8)); //Java 8
connection.setRequestProperty("Authorization", "Basic "+encoded);
然后正常使用连接。
如果您使用Java 7或更低版本,则需要一种将String编码为Base64的方法,例如:
byte[] message = (username+":"+password).getBytes("UTF-8");
String encoded = javax.xml.bind.DatatypeConverter.printBase64Binary(message);
是的,这就是为了使用Basic Auth而必须做的。上述代码设置请求属性应该在打开连接之后并在获取输入或输出流之前立即执行。