/** * @param urlString This string should include the ApiKey but not any auth data. * @return * @throws IOException */ private HttpURLConnection createRealHttpURLConnection(final String urlString) throws IOException { URL url; try { url = AccessController.doPrivileged( new PrivilegedExceptionAction<URL>() { @Override public URL run() throws MalformedURLException { return new URL(urlString); } }); } catch (PrivilegedActionException e) { throw (MalformedURLException) e.getCause(); } // If an HTTP proxy is defined, open the connection with a java.net.Proxy HttpURLConnection connection = null; if (loginInfo.getProxy() != null && loginInfo.getProxy().isHTTP()) { LoginInfoClientProxy loginProxy = loginInfo.getProxy(); Proxy javaNetProxy = new Proxy( Proxy.Type.HTTP, new InetSocketAddress( loginProxy.getProxyURL().getHost(), loginProxy.getProxyURL().getPort())); connection = (HttpURLConnection) url.openConnection(javaNetProxy); } else { connection = (HttpURLConnection) url.openConnection(); } addAuthToConnection(connection); String userAgent = loginInfo.getUserAgent(); if (userAgent != null && !userAgent.isEmpty()) { connection.setRequestProperty("User-Agent", userAgent); } return connection; }
/** * 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); } }