/** * Adds authentication credentials to the connection. * * <p>For basic auth credentials, both username *and* password must be set in order for this to * happen and it is an error for only one to be set. * * @throws AssertionError if precisely one of {username, password} is set. */ private void addAuthToConnection(HttpURLConnection connection) { if (loginInfo.getUserId() != null && loginInfo.getPassword() == null) { throw new AssertionError( "userId is set but password is null. Either both or neither must be set."); } if (loginInfo.getUserId() == null && loginInfo.getPassword() != null) { throw new AssertionError( "password is set but userId is null. Either both or neither must be set."); } // The username and password are added to the connection as a basic auth // Authorization header if (loginInfo.getUserId() != null && loginInfo.getPassword() != null) { String userpass = loginInfo.getUserId() + ":" + loginInfo.getPassword(); String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary( userpass.getBytes(Charset.forName("UTF-8"))); connection.setRequestProperty("Authorization", basicAuth); } // If a proxy is defined and a userid and password are defined add the proxy // authorisation to the connection. if ((loginInfo.getProxy() != null) && (loginInfo.getProxy().getProxyUserid() != null) && (loginInfo.getProxy().getProxyPassword() != null)) { String proxyUser = loginInfo.getProxy().getProxyUserid(); String proxyPwd = loginInfo.getProxy().getProxyPassword(); String proxyUidAndPwd = proxyUser + ":" + proxyPwd; String proxyBasicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary( proxyUidAndPwd.getBytes(Charset.forName("UTF-8"))); connection.setRequestProperty("Proxy-Authorization", proxyBasicAuth); } }