Method to open/establish a URLConnection.

@param url The URL to connect to.
@param proxy The proxy configuration.
@return {@link URLConnection}
@throws IOException
337839
private static URLConnection getConnection(String url, final ProxyConfig proxy) throws IOException {
        URLConnection conn = null;

        if (proxy != null && proxy.getProxyUser() != null) {
            Authenticator.setDefault(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(proxy.getProxyUser(), proxy.getProxyPassword().toCharArray());
                }

            });
        }

        if (proxy != null) {
            Proxy thisProxy = new Proxy(proxy.getProxyType(), new InetSocketAddress(proxy.getProxyHost(), proxy.getProxyPort()));
            conn = new URL(url).openConnection(thisProxy);
        } else {
            conn = new URL(url).openConnection();
        }

        return conn;
    }
548557
public static org.jsoup.nodes.Document getDocumentFromUrl(String url) throws IOException {
        return Jsoup.connect(url).get();
    }
730201
protected HttpURLConnection generateConn() throws IOException {
        HttpURLConnection conn;
        conn = (HttpURLConnection) new URL(url).openConnection();
        return conn;
    }
732514
private void jenkins48775workaround(Proxy proxy, URL url) {
        if ("https".equals(url.getProtocol()) && !authCacheSeeded && proxy != Proxy.NO_PROXY) {
            HttpURLConnection preAuth = null;
            try {
                // We do not care if there is anything at this URL, all we care is that it is using the proxy
                preAuth = (HttpURLConnection) new URL("http", url.getHost(), -1, "/").openConnection(proxy);
                preAuth.setRequestMethod("HEAD");
                preAuth.connect();
            } catch (IOException e) {
                // ignore, this is just a probe we don't care at all
            } finally {
                if (preAuth != null) {
                    preAuth.disconnect();
                }
            }
            authCacheSeeded = true;
        } else if ("https".equals(url.getProtocol())){
            // if we access any http url using a proxy then the auth cache will have been seeded
            authCacheSeeded = authCacheSeeded || proxy != Proxy.NO_PROXY;
        }
    }
1107663
public void setUrl(String url) throws IOException {
    if (failException != null) {
      throw failException;
    }

    sessionInfo.url = url;

    SessionInfo newInfo = new SessionInfo(sessionInfo);
    cmNotifier.addCall(
      new ClusterManagerService.sessionUpdateInfo_args(sessionId, newInfo));
  }
1027057
private Request createTunnel(int readTimeout, int writeTimeout, Request tunnelRequest,
      HttpUrl url) throws IOException {
    // Make an SSL Tunnel on the first message pair of each SSL + proxy connection.
    String requestLine = "CONNECT " + Util.hostHeader(url, true) + " HTTP/1.1";
    while (true) {
      Http1ExchangeCodec tunnelCodec = new Http1ExchangeCodec(null, null, source, sink);
      source.timeout().timeout(readTimeout, MILLISECONDS);
      sink.timeout().timeout(writeTimeout, MILLISECONDS);
      tunnelCodec.writeRequest(tunnelRequest.headers(), requestLine);
      tunnelCodec.finishRequest();
      Response response = tunnelCodec.readResponseHeaders(false)
          .request(tunnelRequest)
          .build();
      tunnelCodec.skipConnectBody(response);

      switch (response.code()) {
        case HTTP_OK:
          // Assume the server won't send a TLS ServerHello until we send a TLS ClientHello. If
          // that happens, then we will have buffered bytes that are needed by the SSLSocket!
          // This check is imperfect: it doesn't tell us whether a handshake will succeed, just
          // that it will almost certainly fail because the proxy has sent unexpected data.
          if (!source.getBuffer().exhausted() || !sink.buffer().exhausted()) {
            throw new IOException("TLS tunnel buffered too many bytes!");
          }
          return null;

        case HTTP_PROXY_AUTH:
          tunnelRequest = route.address().proxyAuthenticator().authenticate(route, response);
          if (tunnelRequest == null) throw new IOException("Failed to authenticate with proxy");

          if ("close".equalsIgnoreCase(response.header("Connection"))) {
            return tunnelRequest;
          }
          break;

        default:
          throw new IOException(
              "Unexpected response code for CONNECT: " + response.code());
      }
    }
  }
449348
private InputStream connect(String url) throws IOException {
		URLConnection conn = new URL(URL_BASE + url).openConnection();
		conn.setConnectTimeout(CONNECT_TIMEOUT);
		conn.setReadTimeout(READ_TIMEOUT);
		conn.setRequestProperty("User-Agent", USER_AGENT);
		return conn.getInputStream();
	}
1039982
public static Socket createSocket(UrlParser urlParser, String host) throws IOException {
    return socketHandler.apply(urlParser, host);
  }
733504
protected HttpURLConnection createHttpURLConnection(final String url) throws IOException {

    URL sendUrl = new URL(url);

    HttpURLConnection con;

    if (StringUtils.isNotBlank(proxyHost) && proxyPort != null) {

      Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
      con = (HttpURLConnection) sendUrl.openConnection(proxy);
      if (StringUtils.isNotBlank(proxyUsername)) {
        String passwd = proxyPassword != null ? proxyPassword : "";
        String authValue = proxyUsername + ":" + passwd;
        String headerValue = Base64.encodeBase64String(authValue.getBytes(
            StandardCharsets.UTF_8));
        con.setRequestProperty("Proxy-Authorization", "Basic " + headerValue);
      }

    } else {

      con = (HttpURLConnection) sendUrl.openConnection();
    }

    try {
      if (url.toLowerCase().startsWith("https")) {
        HttpsURLConnection secCon = (HttpsURLConnection) con;
        secCon.setHostnameVerifier(createAllHostnamesVerifier());
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, createTrustAllManagers(), new SecureRandom());
        secCon.setSSLSocketFactory(sc.getSocketFactory());
      }

    } catch (NoSuchAlgorithmException | KeyManagementException e) {
      throw new IOException(e);
    }

    return con;
  }
149955
public void open() throws IOException {
        LOG.trace("enter HttpConnection.open()");

        final String host = (proxyHostName == null) ? hostName : proxyHostName;
        final int port = (proxyHostName == null) ? portNumber : proxyPortNumber;
        assertNotOpen();
        
        if (LOG.isDebugEnabled()) {
            LOG.debug("Open connection to " + host + ":" + port);
        }
        
        try {
            if (this.socket == null) {
                usingSecureSocket = isSecure() && !isProxied();
                // use the protocol's socket factory unless this is a secure
                // proxied connection
                ProtocolSocketFactory socketFactory = null;
                if (isSecure() && isProxied()) {
                    Protocol defaultprotocol = Protocol.getProtocol("http");
                    socketFactory = defaultprotocol.getSocketFactory();
                } else {
                    socketFactory = this.protocolInUse.getSocketFactory();
                }
                this.socket = socketFactory.createSocket(
                            host, port, 
                            localAddress, 0,
                            this.params);
            }

            /*
            "Nagling has been broadly implemented across networks, 
            including the Internet, and is generally performed by default 
            - although it is sometimes considered to be undesirable in 
            highly interactive environments, such as some client/server 
            situations. In such cases, nagling may be turned off through 
            use of the TCP_NODELAY sockets option." */

            socket.setTcpNoDelay(this.params.getTcpNoDelay());
            socket.setSoTimeout(this.params.getSoTimeout());
            
            int linger = this.params.getLinger();
            if (linger >= 0) {
                socket.setSoLinger(linger > 0, linger);
            }
            
            int sndBufSize = this.params.getSendBufferSize();
            if (sndBufSize >= 0) {
                socket.setSendBufferSize(sndBufSize);
            }        
            int rcvBufSize = this.params.getReceiveBufferSize();
            if (rcvBufSize >= 0) {
                socket.setReceiveBufferSize(rcvBufSize);
            }        
            int outbuffersize = socket.getSendBufferSize();
            if ((outbuffersize > 2048) || (outbuffersize <= 0)) {
                outbuffersize = 2048;
            }
            int inbuffersize = socket.getReceiveBufferSize();
            if ((inbuffersize > 2048) || (inbuffersize <= 0)) {
                inbuffersize = 2048;
            }
            inputStream = new BufferedInputStream(socket.getInputStream(), inbuffersize);
            outputStream = new BufferedOutputStream(socket.getOutputStream(), outbuffersize);
            isOpen = true;
        } catch (IOException e) {
            // Connection wasn't opened properly
            // so close everything out
            closeSocketAndStreams();
            throw e;
        }
    }
802560
public void setProxy(String proxyhost, int proxyport) {
		proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(proxyhost, proxyport));
	}
1146314
protected Proxy selectProxy(URL requestTokenURL) {
    try {
      List<Proxy> selectedProxies = getProxySelector().select(requestTokenURL.toURI());
      return selectedProxies.isEmpty() ? Proxy.NO_PROXY : selectedProxies.get(0);
    }
    catch (URISyntaxException e) {
      throw new IllegalArgumentException(e);
    }
  }
348078
protected HttpURLConnection openConnection(String url) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS);
    connection.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLIS);
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestProperty("User-Agent", USER_AGENT);
    connection.setDoInput(true);
    return connection;
  }
1097662
protected HttpURLConnection openConnection(String url, Map<String, String> header) throws IOException {
		// Initialize connection
		URL urlObj = null;
		HttpURLConnection conn = null;

		int redirectCount = 0;
		boolean redirect = true;
		while (redirect) {
			if (redirectCount > 10) {
				throw new ProtocolException("Too many redirects: " + redirectCount);
			}

			if (conn == null) {
				urlObj = new URL(url);
			} else {
				// get redirect url from "location" header field
				urlObj = new URL(conn.getHeaderField("Location"));
			}

			// open the new connection again
			conn = (HttpURLConnection) urlObj.openConnection();
			conn.setRequestMethod(header.get("method"));
			conn.setInstanceFollowRedirects(true);

			// Set output if PUT or POST
			if (conn.getRequestMethod() == "POST" || conn.getRequestMethod() == "PUT") {
				conn.setDoOutput(true);
			}

			// Set request header
			for (Map.Entry<String, String> headerAttr : header.entrySet()) {
				conn.addRequestProperty(headerAttr.getKey(), headerAttr.getValue());
			}

			// Check if redirect
			redirect = false;
			if (conn.getRequestMethod() == "GET") {
				int status = conn.getResponseCode();
				if (status != HttpURLConnection.HTTP_OK) {
					if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER)
						redirect = true;
					redirectCount++;
				}
			}
		}

		return conn;
	}
1089829
private HttpURLConnection openConnection(URL url) throws IOException {
              HttpURLConnection connection = createConnection(url);
              connection.setUseCaches(true);
              connection.setDoInput(true);
              return connection;
       }
1086160
function WebClientConnection(options) {

    var url = window.location.host.split(':')[0];
    if (options && options.proxyUrl) {
        url = options.proxyUrl;
    }

    this.createProxySocket('http://' + url, 33331);

    EventEmitter.call(this);
}
974705
def connect(self, url):
        

        headers = httputil.HTTPHeaders({'Content-Type': APPLICATION_JSON})
        request = httpclient.HTTPRequest(url=url,
                                         connect_timeout=self.connect_timeout,
                                         request_timeout=self.request_timeout,
                                         headers=headers)
        ws = websocket_connect(url)
        ws.add_done_callback(self._connect_callback)