2 // Getdown - application installer, patcher and launcher
3 // Copyright (C) 2004-2018 Getdown authors
4 // https://github.com/threerings/getdown/blob/master/LICENSE
6 package com.threerings.getdown.util;
8 import java.io.IOException;
9 import java.net.HttpURLConnection;
10 import java.net.Proxy;
12 import java.net.URLConnection;
13 import java.net.URLDecoder;
15 import com.threerings.getdown.data.SysProps;
17 import static java.nio.charset.StandardCharsets.UTF_8;
19 public class ConnectionUtil
22 * Opens a connection to a URL, setting the authentication header if user info is present.
23 * @param proxy the proxy via which to perform HTTP connections.
24 * @param url the URL to which to open a connection.
25 * @param connectTimeout if {@code > 0} then a timeout, in seconds, to use when opening the
26 * connection. If {@code 0} is supplied, the connection timeout specified via system properties
27 * will be used instead.
28 * @param readTimeout if {@code > 0} then a timeout, in seconds, to use while reading data from
29 * the connection. If {@code 0} is supplied, the read timeout specified via system properties
30 * will be used instead.
32 public static URLConnection open (Proxy proxy, URL url, int connectTimeout, int readTimeout)
35 URLConnection conn = url.openConnection(proxy);
37 // configure a connect timeout, if requested
38 int ctimeout = connectTimeout > 0 ? connectTimeout : SysProps.connectTimeout();
40 conn.setConnectTimeout(ctimeout * 1000);
43 // configure a read timeout, if requested
44 int rtimeout = readTimeout > 0 ? readTimeout : SysProps.readTimeout();
46 conn.setReadTimeout(rtimeout * 1000);
49 // If URL has a username:password@ before hostname, use HTTP basic auth
50 String userInfo = url.getUserInfo();
51 if (userInfo != null) {
52 // Remove any percent-encoding in the username/password
53 userInfo = URLDecoder.decode(userInfo, "UTF-8");
54 // Now base64 encode the auth info and make it a single line
55 String encoded = Base64.encodeToString(userInfo.getBytes(UTF_8), Base64.DEFAULT).
56 replaceAll("\\n","").replaceAll("\\r", "");
57 conn.setRequestProperty("Authorization", "Basic " + encoded);
64 * Opens a connection to a http or https URL, setting the authentication header if user info is
65 * present. Throws a class cast exception if the connection returned is not the right type. See
66 * {@link #open} for parameter documentation.
68 public static HttpURLConnection openHttp (
69 Proxy proxy, URL url, int connectTimeout, int readTimeout) throws IOException
71 return (HttpURLConnection)open(proxy, url, connectTimeout, readTimeout);