Connects to the given HTTP URL and configure time out, to avoid infinite hang.
334730
private static HttpURLConnection open(URL url) throws IOException {
        HttpURLConnection c = (HttpURLConnection)url.openConnection();
        c.setReadTimeout(TIMEOUT);
        c.setConnectTimeout(TIMEOUT);
        return c;
    }
1199050
def connect(url, prefix=None, **kwargs):
    
    return connection(url, prefix=get_prefix(prefix), **kwargs)
943873
public void connect (int timeout, String host, int tcpPort) throws IOException {
		connect(timeout, InetAddress.getByName(host), tcpPort, -1);
	}
990315
def rest_get(url, timeout):
    ''''''
    try:
        response = requests.get(url, timeout=timeout)
        return response
    except Exception as e:
        print('Get exception {0} when sending http get to url {1}'.format(str(e), url))
        return None
357337
def urlopen(url, timeout=20, redirects=None):
    """"""
    scheme, host, path, params, query, frag = urlparse(url)

    if not scheme in ('http', 'https'):
        return urllib.urlopen(url)
    if params: path = '%s;%s' % (path, params)
    if query:  path = '%s?%s' % (path, query)
    if frag:   path = '%s#%s' % (path, frag)

    if scheme == 'https':
        # If ssl is not compiled into Python, you will not get an exception
        # until a conn.endheaders() call.   We need to know sooner, so use
        # getattr.
        try:
            import M2Crypto
        except ImportError:
            if not hasattr(socket, 'ssl'):
                raise RuntimeError, 'no built-in SSL Support'

            conn = TimeoutHTTPS(host, None, timeout)
        else:
            ctx = M2Crypto.SSL.Context()
            ctx.set_session_timeout(timeout)
            conn = M2Crypto.httpslib.HTTPSConnection(host, ssl_context=ctx)
            conn.set_debuglevel(1)

    else:
        conn = TimeoutHTTP(host, None, timeout)

    conn.putrequest('GET', path)
    conn.putheader('Connection', 'close')
    conn.endheaders()
    response = None
    while 1:
        response = conn.getresponse()
        if response.status != 100:
            break
        conn._HTTPConnection__state = httplib._CS_REQ_SENT
        conn._HTTPConnection__response = None

    status = response.status

    # If we get an HTTP redirect, we will follow it automatically.
    if status >= 300 and status < 400:
        location = response.msg.getheader('location')
        if location is not None:
            response.close()
            if redirects is not None and redirects.has_key(location):
                raise RecursionError(
                    'Circular HTTP redirection detected.'
                    )
            if redirects is None:
                redirects = {}
            redirects[location] = 1
            return urlopen(location, timeout, redirects)
        raise HTTPResponse(response)

    if not (status >= 200 and status < 300):
        raise HTTPResponse(response)

    body = StringIO(response.read())
    response.close()
    return body
1220444
function connect(socketURL) {
        disconnect().done(function () {
            _socket = new WebSocket(socketURL);
            _socket.onmessage = _onMessage;
            _socket.onopen = _onConnect;
            _socket.onclose = _onDisconnect;
            _socket.onerror = _onError;
        });
    }
845110
def wait_for_connection(self, timeout=None):
        
        if timeout is not None:
            wait_time = timeout / 10.0
        else:
            wait_time = None
        with self.__connect_wait_condition:
            while self.running and not self.is_connected() and not self.connection_error:
                self.__connect_wait_condition.wait(wait_time)
        if not self.running or not self.is_connected():
            raise exception.ConnectFailedException()
158567
def a_connection_timeout(ctx):
    """"""
    prompt = ctx.ctrl.after
    ctx.msg = "Received the jump host prompt: '{}'".format(prompt)
    ctx.device.connected = False
    ctx.finished = True
    raise ConnectionTimeoutError("Unable to connect to the device.", ctx.ctrl.hostname)
305594
public void setConnectTimeout(int millis) {
		ClientHttpRequestFactory f = getRequestFactory();
		if (f instanceof SimpleClientHttpRequestFactory) {
			((SimpleClientHttpRequestFactory) f).setConnectTimeout(millis);
		}
		else {
			((HttpComponentsClientHttpRequestFactory) f).setConnectTimeout(millis);
		}
	}
242258
def connect(self, timeout=10):
        

        # connect to a local address by default
        # if listening to all addresses (IPv4 or IPv6)
        if self._host == "0.0.0.0":
            host = "127.0.0.1"
        elif self._host == "::":
            host = "::1"
        else:
            host = self._host

        begin = time.time()
        connection_success = False
        last_exception = None
        while time.time() - begin < timeout:
            yield from asyncio.sleep(0.01)
            try:
                self._reader, self._writer = yield from asyncio.wait_for(asyncio.open_connection(host, self._port), timeout=1)
            except (asyncio.TimeoutError, OSError) as e:
                last_exception = e
                continue
            connection_success = True
            break

        if not connection_success:
            raise DynamipsError("Couldn't connect to hypervisor on {}:{} :{}".format(host, self._port, last_exception))
        else:
            log.info("Connected to Dynamips hypervisor after {:.4f} seconds".format(time.time() - begin))

        try:
            version = yield from self.send("hypervisor version")
            self._version = version[0].split("-", 1)[0]
        except IndexError:
            self._version = "Unknown"

        # this forces to send the working dir to Dynamips
        yield from self.set_working_dir(self._working_dir)
236029
public static Patch patch(String url, byte[] content, int connectTimeout, int readTimeout) {

        try {
            return new Patch(url, content, connectTimeout, readTimeout);
        } catch (Exception e) {
            throw new HttpException("Failed URL: " + url, e);
        }
    }
361580
private HttpURLConnection openConnection(String uri, String method) {
        for (String host : hosts) {
            try {
                URL templateUrl = new URL("http://" + host  + uri);
                HttpURLConnection connection = ( HttpURLConnection ) templateUrl.openConnection();
                connection.setRequestMethod(method);
                connection.setConnectTimeout(timeout);
                connection.setUseCaches(false);
                if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) {
                    connection.setDoOutput(true);
                }
                connection.connect();

                return connection;
            } catch (IOException e) {
                LOGGER.error("Error connecting to {}: {}", host, e);
            }
        }

        return null;
    }
1313668
public void asyncRequest(String host,int port,HttpRequest request,final CallBack<HttpResponse> callback,long timeOut)
	{
		synchronized (request) {
			final HttpListener listener=new HttpListener(request);
			final NettyClient client=new NettyClient(config,new InetSocketAddress(host, port),new HttpClientInitHandler(listener));
			client.start();
			if(callback!=null)
			{
				scheduExec.execute(new Runnable() {
					@Override
					public void run() {
						HttpResponse result=listener.waitResponse(timeOut);
						callback.call(result!=null,Optional.ofNullable(result));
						client.stop();
					}
				});
			}
		}
	}
809474
public static final HttpClient getClient(int timeout) {
        HttpClientBuilder client = HttpClientBuilder.create();
        // set the connection manager
        client.setConnectionManager(connectionManager);
        // dont retry
        client.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
        // establish a connection within x seconds
        RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout).build();
        client.setDefaultRequestConfig(config);
        // no redirects
        client.disableRedirectHandling();
        // set custom ua
        client.setUserAgent(userAgent);
        // set the proxy if the user has one set
        if ((System.getProperty("http.proxyHost") != null) && (System.getProperty("http.proxyPort") != null)) {
            HttpHost proxy = new HttpHost(System.getProperty("http.proxyHost").toString(), Integer.valueOf(System.getProperty("http.proxyPort")));
            client.setProxy(proxy);
        }
        return client.build();
    }
1156549
def _startHungConnectionTimer(self):
        
        def hungConnection():
            self._hung_callback()
            self._hungConnectionTimer = None
            self.transport.loseConnection()
        self._hungConnectionTimer = self._reactor.callLater(
            self._HUNG_CONNECTION_TIMEOUT, hungConnection)
320179
def connect
      http = Net::HTTP.new(host, port)
      http.use_ssl = ssl

      begin
        yield http
      rescue *HTTP_ERRORS => exception
        raise ConnectionError, "#{exception.class.name}: #{exception.message}"
      end
    end
993325
async def _open_connection_http(self, location):
        '''
        
        '''
        sock = await connect_tcp(location[0], location[1], bind_host=self.source_address)
        sock._active = True
        return sock