Force a connection attempt via HTTP GET.
196884
def device_connect(device_id):
    
    success = False
    if device_id in devices:
        devices[device_id].connect()
        success = True
    return jsonify(success=success)
124431
def _get_url(url):
    """"""
    try:
        data = HTTP_SESSION.get(url, stream=True)
        data.raise_for_status()
    except requests.exceptions.RequestException as exc:
        raise FetcherException(exc)

    return data
670865
def prepare_http_connection
      conn = HTTPClient.new(options[:proxy] || self.class.proxy)
      set_http_connection_options(conn, options)
      conn
    end
183072
def connect(self, urls=None, **overrides):
        """"""
        if urls is not None:
            overrides['urls'] = urls
        return self.where(accept='CONNECT', **overrides)
1246855
def do_get(self, uri):
        
        self.validate_resource_uri(uri)
        return self._connection.get(uri)
726316
def request_failed exception, req, connection # :nodoc:
    due_to = "(due to #{exception.message} - #{exception.class})"
    message = "too many connection resets #{due_to} #{error_message connection}"

    finish connection

    raise Error, message, exception.backtrace
  end
530073
def get(self, relpath=None, params=None):
    
    for retry in xrange(self.retries + 1):
      if retry:
        time.sleep(self.retry_sleep)
      try:
        return self.invoke("GET", relpath, params)
      except (socket.error, urllib2.URLError) as e:
        if "timed out" in str(e).lower():
          log_message = "Timeout issuing GET request for %s." \
              % (self._join_uri(relpath), )
          if retry < self.retries:
            log_message += " Will retry."
          else:
            log_message += " No retries left."
          LOG.warn(log_message, exc_info=True)
        else:
          raise
    else:
      raise e
290701
def _connection_failed(self, link_uri, msg):
        """"""
        print('Connection to %s failed: %s' % (link_uri, msg))
        self.is_connected = False
284233
private <T> T execute(String url, Class<T> returnType, Object requestObject) throws Exception {
        URLConnection connection = new URL(url).openConnection();
        if (!(connection instanceof HttpURLConnection)) {
            throw new IllegalStateException("Not an http connection! " + connection);
        }
        HttpURLConnection httpConnection = (HttpURLConnection) connection;
        httpConnection.setUseCaches(false);
        httpConnection.setDefaultUseCaches(false);
        httpConnection.setDoInput(true);

        /*
         * With followRedirects enabled, simple URL redirects work as expected. But with port redirects (http->https)
         * followRedirects doesn't work and a HTTP 302 code is returned instead (ARQ-1365).
         *
         * In order to handle all redirects in one place, followRedirects is set to false and all HTTP 302 response codes are
         * treated accordingly within the execute method.
         */
        httpConnection.setInstanceFollowRedirects(false);

        try {

            if (requestObject != null) {
                httpConnection.setRequestMethod("POST");
                httpConnection.setDoOutput(true);
                httpConnection.setRequestProperty("Content-Type", "application/octet-stream");
            }

            if (requestObject != null) {
                ObjectOutputStream ous = new ObjectOutputStream(httpConnection.getOutputStream());
                try {
                    ous.writeObject(requestObject);
                } catch (Exception e) {
                    throw new RuntimeException("Error sending request Object, " + requestObject, e);
                } finally {
                    ous.flush();
                    ous.close();
                }
            }

            try {
                httpConnection.getResponseCode();
            } catch (ConnectException e) {
                return null; // Could not connect
            }
            if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                ObjectInputStream ois = new ObjectInputStream(httpConnection.getInputStream());
                Object o;
                try {
                    o = ois.readObject();
                } finally {
                    ois.close();
                }

                if (!returnType.isInstance(o)) {
                    throw new IllegalStateException(
                        "Error reading results, expected a " + returnType.getName() + " but got "
                            + o);
                }
                return returnType.cast(o);
            } else if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
                return null;
            } else if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
                String redirectUrl = httpConnection.getHeaderField("Location");
                return execute(redirectUrl, returnType, requestObject);
            } else if (httpConnection.getResponseCode() != HttpURLConnection.HTTP_NOT_FOUND) {
                throw new IllegalStateException("Error launching test at " + url + ". " + "Got "
                    + httpConnection.getResponseCode() + " (" + httpConnection.getResponseMessage() + ")");
            }
        } finally {
            httpConnection.disconnect();
        }
        return null;
    }
323199
def _make_request(self, path, method='GET', params_=None):
        """"""
        uri = self.api_root + path
        if params_:
            params_['text_format'] = self.response_format
        else:
            params_ = {'text_format': self.response_format}

        # Make the request
        response = None
        try:
            response = self._session.request(method, uri,
                                            timeout=self.timeout,
                                            params=params_)
        except Timeout as e:
            print("Timeout raised and caught:\n{e}".format(e=e))

        # Enforce rate limiting
        time.sleep(max(self._SLEEP_MIN, self.sleep_time))
        return response.json()['response'] if response else None
1245591
def get(self, url=None, params=None, retry=True):
        '''
        
        '''
        headers = self._gen_headers(self.access_token, url)
        attempts = 1
        while attempts <= HTTP_ATTEMPTS_MAX:
            try:
                res = requests.get(url,
                                   headers=headers,
                                   params=params,
                                   timeout=15,
                                   verify=self.certs)
                res.raise_for_status()
                return res.json()
            except requests.exceptions.RequestException as e:
                attempts += 1
                if res.status_code in [400]:
                    raise e
                elif retry and res.status_code in [403]:
                    self.relogin_oauth2()
473711
def _call_retry(self, force_retry):
        """"""
        last_exception = None
        for i in range(self.max_attempts):
            try:
                log.info("Calling %s %s" % (self.method, self.url))
                response = self.requests_method(
                    self.url,
                    data=self.data,
                    params=self.params,
                    headers=self.headers,
                    timeout=(self.connect_timeout, self.read_timeout),
                    verify=self.verify_ssl,
                )

                if response is None:
                    log.warn("Got response None")
                    if self._method_is_safe_to_retry():
                        delay = 0.5 + i * 0.5
                        log.info("Waiting %s sec and Retrying since call is a %s" % (delay, self.method))
                        time.sleep(delay)
                        continue
                    else:
                        raise PyMacaronCoreException("Call %s %s returned empty response" % (self.method, self.url))

                return response

            except Exception as e:

                last_exception = e

                retry = force_retry

                if isinstance(e, ReadTimeout):
                    # Log enough to help debugging...
                    log.warn("Got a ReadTimeout calling %s %s" % (self.method, self.url))
                    log.warn("Exception was: %s" % str(e))
                    resp = e.response
                    if not resp:
                        log.info("Requests error has no response.")
                        # TODO: retry=True? Is it really safe?
                    else:
                        b = resp.content
                        log.info("Requests has a response with content: " + pprint.pformat(b))
                    if self._method_is_safe_to_retry():
                        # It is safe to retry
                        log.info("Retrying since call is a %s" % self.method)
                        retry = True

                elif isinstance(e, ConnectTimeout):
                    log.warn("Got a ConnectTimeout calling %s %s" % (self.method, self.url))
                    log.warn("Exception was: %s" % str(e))
                    # ConnectTimeouts are safe to retry whatever the call...
                    retry = True

                if retry:
                    continue
                else:
                    raise e

        # max_attempts has been reached: propagate the last received Exception
        if not last_exception:
            last_exception = Exception("Reached max-attempts (%s). Giving up calling %s %s" % (self.max_attempts, self.method, self.url))
        raise last_exception
467158
function tryRequire(filePath) {
  let resolvedPath = req.resolve(filePath);

  if (resolvedPath) {
    return req(resolvedPath);
  }

  return undefined;
}
238225
private HttpURLConnection getConnection(String uri, String postJson, String token) throws IOException {
		int tries = 0;
		IOException last = null;

		while (tries++ <= retries) {
			try {
				return getConnectionOnce(uri, postJson, token);
			} catch (IOException ex) {
				last = ex;
			}
		}

		throw last;
	}
1089829
private HttpURLConnection openConnection(URL url) throws IOException {
              HttpURLConnection connection = createConnection(url);
              connection.setUseCaches(true);
              connection.setDoInput(true);
              return connection;
       }
605133
def get(self, url, params=None, callback=None, retry=0, **kwargs):
        """"""
        kwargs.setdefault("allow_redirects", True)
        return self.request(
            "get", url=url, params=params, callback=callback, retry=retry, **kwargs
        )
106312
def connection_made(self, address):
        """"""
        self._proxy = PickleProxy(self.loop, self)
        for d in self._proxy_deferreds:
            d.callback(self._proxy)