-- HTTP REQUEST -------------------------------------------------------------
11748
function makeHttpRequest(encoding, next) {
  var start = Date.now();

  request(
    {
      url: 'http://localhost:1337/' + encoding,
      method: 'GET',
      headers: {
        'accept-encoding': encoding,
      },
    },
    function(err, data, body) {
      var time = Date.now() - start;

      console.log(encoding.toUpperCase() + ' COMPRESSION:');
      console.log('  status:', data.statusCode);
      console.log('  body  :', body);
      console.log('  time  :', time);

      common.verify(function() {
        data.headers.should.not.have.property('content-encoding');
        body.should.equal('hello, ' + encoding);
      });

      console.log();

      next();
    }
  );
}
308504
public function parseRequest()
	{
		$this->request = Input::all();

		$uri = Route::getCurrentRoute()->parametersWithoutNulls();

		if($uri)
		{
			$this->request = array_merge($uri, $this->request);
		}

		$this->setApiContext();
	}
249152
public function do_request($request)
    {
        $http = [];

        $http['method'] = $request->method;

        $headers = [];
        foreach ($request->headers as $k => $v) {
            $headers[] = is_string($k) ? "$k: $v" : $v;
        }

        if (isset($request->options['proxy'])) {
            $parts = parse_url($request->options['proxy']);
            if ($parts['scheme'] !== 'http') {
                throw new NotSupportedException(['only support http type proxy: `:proxy`', 'proxy' => $request->options['proxy']]);
            }

            if (isset($parts['pass'])) {
                $headers[] = 'Proxy-Authorization: Basic ' . base64_encode($parts['user'] . ':' . $parts['pass']);
            }
            $http['proxy'] = 'tcp://' . $parts['host'] . ':' . (isset($parts['port']) ? $parts['port'] : '80');
        }

        $http['header'] = $headers;

        if (is_string($request->body)) {
            $http['content'] = $request->body;
        } elseif (is_array($request->body)) {
            if (isset($options['Content-Type']) && strpos($request->headers['Content-Type'], 'json') !== false) {
                $http['content'] = json_encode($request->body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            } else {
                $http['content'] = http_build_query($request->body);
            }
        }

        $http['timeout'] = $request->options['timeout'];
        $http['ignore_errors'] = true;

        $ssl = [];
        $ssl['verify_peer'] = $request->options['verify_peer'];
        if (isset($request->options['allow_self_signed'])) {
            $ssl['allow_self_signed'] = $request->options['allow_self_signed'];
        } else {
            $ssl['allow_self_signed'] = !$request->options['verify_peer'];
        }

        if (isset($request->options['cafile'])) {
            $ssl['cafile'] = $this->alias->resolve($request->options['cafile']);
        }

        $start_time = microtime(true);

        if (!$stream = @fopen($request->url, 'rb', false, stream_context_create(['http' => $http, 'ssl' => $ssl]))) {
            throw new ConnectionException(['`:url`: `:last_error_message`', 'url' => $request->url]);
        }
        $meta = stream_get_meta_data($stream);
        $body = stream_get_contents($stream);
        fclose($stream);

        $process_time = round(microtime(true) - $start_time, 3);

        $headers = $meta['wrapper_data'];

        for ($i = count($headers) - 1; $i >= 0; $i--) {
            $header = $headers[$i];
            /** @noinspection NotOptimalIfConditionsInspection */
            if (strpos($header, ':') === false && $headers !== '') {
                break;
            }
        }

        if ($i !== 0) {
            $headers = array_slice($headers, $i);
        }

        $content_type = null;
        foreach ($headers as $header) {
            if (strpos($header, 'Content-Type:') === 0) {
                $content_type = trim(substr($header, 13));
                break;
            }
        }

        $http_code = null;
        if ($headers && preg_match('#\d{3}#', $headers[0], $match)) {
            $http_code = (int)$match[0];
        }

        $response = new Response();
        $response->url = $request->url;
        $response->remote_ip = null;
        $response->http_code = $http_code;
        $response->headers = $headers;
        $response->process_time = 0;
        $response->content_type = $content_type;
        $response->body = $body;
        $response->process_time = $process_time;

        return $response;
    }
1055809
function request( url, args ) {
    return new Promise( function( resolve, reject ) {
        const xhr = new XMLHttpRequest();
        xhr.open( "POST", url, true ); // true is for async.
        xhr.onload = () => {
            const DONE = 4;
            if ( xhr.readyState !== DONE ) return;

            console.info( "xhr.status=", xhr.status );
            console.info( "xhr.responseText=", xhr.responseText );
            if ( xhr.status === 200 ) resolve( xhr.responseText );
            /*
            else reject( {
                id: exports.HTTP_ERROR,
                msg: "(" + xhr.status + ") " + xhr.statusText,
                status: xhr.status
            } );
            */
        };
        xhr.onerror = function() {
            reject( {
                id: exports.HTTP_ERROR,
                err: "HTTP_ERROR (" + xhr.status + ") " + xhr.statusText,
                status: xhr.status
            } );
        };
        const params = Object.keys( args )
            .map( key => `${key}=${encodeURIComponent(args[key])}` )
            .join( "&" );
        xhr.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
        xhr.send( params );
    } );
}
1284223
@Override
  public final synchronized void onHttpRequest(final ParsedHttpRequest parsedHttpRequest,
                                               final HttpServletResponse response)
      throws IOException, ServletException {
    LOG.log(Level.INFO, "HttpServeShellCmdHandler in webserver onHttpRequest is called: {0}",
        parsedHttpRequest.getRequestUri());
    final String queryStr = parsedHttpRequest.getQueryString();

    if (parsedHttpRequest.getTargetEntity().equalsIgnoreCase("Evaluators")) {
      final byte[] b = HttpShellJobDriver.CODEC.encode(queryStr);
      LOG.log(Level.INFO, "HttpServeShellCmdHandler call HelloDriver onCommand(): {0}", queryStr);
      messageHandler.get().onNext(b);

      notify();

      final long endTime = System.currentTimeMillis() + WAIT_TIMEOUT;
      while (cmdOutput == null) {
        final long waitTime = endTime - System.currentTimeMillis();
        if (waitTime <= 0) {
          break;
        }

        try {
          wait(WAIT_TIME);
        } catch (final InterruptedException e) {
          LOG.log(Level.WARNING, "HttpServeShellCmdHandler onHttpRequest InterruptedException: {0}", e);
        }
      }
      if (cmdOutput != null) {
        response.getOutputStream().write(cmdOutput.getBytes(StandardCharsets.UTF_8));
        cmdOutput = null;
      }
    } else if (parsedHttpRequest.getTargetEntity().equalsIgnoreCase("Driver")) {
      final String commandOutput = CommandUtils.runCommand(queryStr);
      response.getOutputStream().write(commandOutput.getBytes(StandardCharsets.UTF_8));
    }
  }
633546
protected void postProcessHttpRequest(HttpUriRequest httpRequest) {
		HttpParams params = httpRequest.getParams();
		HttpProtocolParams.setUseExpectContinue(params, false);
	}
1345297
function httpRequestPromise(method, urlObject) {
  if (method !== 'GET' && method !== 'HEAD') {
    return Promise.reject(new Error('We only support GET or HEAD requests'));
  }

  return new Promise(function (resolve, reject) {
    var httpsRequestOptions = {
      host: urlObject.host,
      method: method,
      path: urlObject.path
    };

    var req = https.request(httpsRequestOptions, function (res) {
      if (res.statusCode !== 200) {
        reject(new Error('Did not get 200 for ' + urlObject.href +
          ', instead got ' + res.statusCode));
        return;
      }

      resolve(res);
    })
    .on('error', function (e) {
      reject(new Error('Got error on ' + urlObject.href + ' - ' + e));
    });

    req.end();
  });
}
540744
public static String request(HttpUriRequest httpUriRequest,
            Charset charSet) {
        try (CloseableHttpResponse response =
                getHttpClient().execute(httpUriRequest)) {
            HttpEntity httpEntity = response.getEntity();
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode >= 200 && statusCode < 300)
                return EntityUtils.toString(httpEntity, charSet);
            throw new IllegalStateException(
                    response.getStatusLine().getStatusCode() + JMString.SPACE
                            + response.getStatusLine().getReasonPhrase());
        } catch (IOException e) {
            throw JMExceptionManager.handleExceptionAndReturnRuntimeEx(log, e,
                    "request", httpUriRequest);
        }
    }
801459
private ServletRequestHandler newPostHttpRequestHandler() {
        return new ServletRequestHandler() {
            /** {@inheritDoc} */
             public JSONAware handleRequest(HttpServletRequest pReq, HttpServletResponse pResp)
                    throws IOException {
                 String encoding = pReq.getCharacterEncoding();
                 InputStream is = pReq.getInputStream();
                 return requestHandler.handlePostRequest(pReq.getRequestURI(),is, encoding, getParameterMap(pReq));
             }
        };
    }
638944
protected <T extends HttpRequestBase> T createHttpRequest(Q request) {
    T httpRequest = createHttpRequestBase(request);

    applyHeaders(httpRequest, request.getHeaders());

    applyPayload(httpRequest, request);

    return httpRequest;
  }
81943
protected void processRequest( HttpServletRequest request,
                                   HttpServletResponse response ) throws ServletException, IOException {
        String authHeader = ((HttpServletRequest)request).getHeader("Authorization");
        String pathInfo= request.getPathInfo();
        
        Object marker = request.getSession().getAttribute("login-required-marker");
        
        if (marker == null && pathInfo.equals("login.do")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.addHeader("WWW-Authenticate", "Basic realm =\"Realm\"");
            request.getSession().setAttribute("login-required-marker", Boolean.FALSE);
            return;
        }

        if (pathInfo.equals("login.do")) {
            response.sendRedirect(request.getContextPath() + "/Console.html");
            return;
        }
        
        String url = request.getRequestURI();
        String servletPath = request.getServletPath();

        request.getSession(true).setAttribute("initial.uri", url);
        logger.debug("Store requested uri " + url);
        
        String dest = url.substring(0, url.indexOf(servletPath));
        response.sendRedirect(dest);
    }
1324327
function request(url, fn) {
    var method = 'GET';

    if ('string' == typeof fn) {
        method = url;
        url = fn;
        fn = arguments[2];
    }

    fn = fn || function () {
    };

    o.ajax({ type: method, url: url })
        .success(function (res) {
            res.error
                ? error(res.error)
                : fn(res);
        });
}
648738
@Override
    public <TResponse> TResponse post(IReturn<TResponse> request) {
        return send(createUrl(request, HttpMethods.Post), HttpMethods.Post, request, request.getResponseType());
    }
46616
function request()
    {
        if (!$this->request) {
            $request = new HttpRequest( new BuildHttpRequest );
            $this->request = $request;
        }

        return $this->request;
    }
637858
function makeHttpRequest(reqHeaders, expectedRes, cacheHitExpected, next) {
  reqHeaders.cookie = _.reduce(reqHeaders.cookie, function(memo, val, name) {
    memo.push(name + '=' + val);
    return memo;
  }, []).join('; ');

  var start = Date.now();

  request({
    url: 'http://localhost:1337',
    method: 'GET',
    headers: reqHeaders
  }, function(err, data, body) {
    var time = Date.now() - start;

    console.log('  status:', data.statusCode);
    console.log('  body  :', body);
    console.log('  time  :', time);

    common.verify(function() {
      JSON.parse(body).should.eql(expectedRes);
      common.shouldUseCache(cacheHitExpected, time);
    });

    next();
  });
}
117029
protected boolean includeRequest(HttpServletRequest request) {
        if (ArrayUtils.isNotEmpty(urlsToInclude)) {
            for (String pathPattern : urlsToInclude) {
                if (pathMatcher.match(pathPattern, HttpUtils.getRequestUriWithoutContextPath(request))) {
                    return true;
                }
            }
        }

        return false;
    }
139882
private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content)
            throws IOException {
        // Validate the requested file ------------------------------------------------------------

        // Get requested file by path info.
        String requestedFile = request.getPathInfo();
        if (logger.isDebugEnabled()) {
            logger.debug("Requested path:" + requestedFile);
        }

        // Check if file is actually supplied to the request URL.
        if (requestedFile == null) {
            logger.debug("No file requested, return 404.");
            // Do your thing if the file is not supplied to the request URL.
            // Throw an exception, or send 404, or show default/warning page, or just ignore it.
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        Configuration rootConfiguration = (Configuration) request.getServletContext().getAttribute(Configuration.class.getName());
        Configuration runtimeConfiguration = rootConfiguration.subset("runtime-settings");

        String basePath = runtimeConfiguration.getString("cache-path");
        int bufferSize = runtimeConfiguration.getInteger("cache-buffer-size", DEFAULT_BUFFER_SIZE);
        long expireTime = runtimeConfiguration.getLong("cache-expire-time", DEFAULT_EXPIRE_TIME);

        // URL-decode the file name (might contain spaces and on) and prepare file object.
        String fDecodedPath = URLDecoder.decode(requestedFile, "UTF-8");
        File file = new File(basePath, fDecodedPath);

        // Check if file actually exists in filesystem.
        if (!file.exists()) {
            logger.debug("Requested file not found, return 404.");
            // Do your thing if the file appears to be non-existing.
            // Throw an exception, or send 404, or show default/warning page, or just ignore it.
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // Prepare some variables. The ETag is an unique identifier of the file.
        String fileName = file.getName();
        long length = file.length();
        long lastModified = file.lastModified();
        String eTag = fileName + "_" + length + "_" + lastModified;
        long expires = System.currentTimeMillis() + expireTime;

        // Validate request headers for caching ---------------------------------------------------
        // If-None-Match header should contain "*" or ETag. If so, then return 304.
        String ifNoneMatch = request.getHeader("If-None-Match");
        if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
            logger.debug("IfNoneMatch/Etag not matching, return 304.");
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            response.setHeader("ETag", eTag); // Required in 304.
            response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
            return;
        }

        // If-Modified-Since header should be greater than LastModified. If so, then return 304.
        // This header is ignored if any If-None-Match header is specified.
        long ifModifiedSince = request.getDateHeader("If-Modified-Since");
        if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
            logger.debug("IfModifiedSince not matching, return 304.");
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            response.setHeader("ETag", eTag); // Required in 304.
            response.setDateHeader("Expires", expires); // Postpone cache with 1 week.
            return;
        }

        // Validate request headers for resume ----------------------------------------------------
        // If-Match header should contain "*" or ETag. If not, then return 412.
        String ifMatch = request.getHeader("If-Match");
        if (ifMatch != null && !matches(ifMatch, eTag)) {
            logger.debug("ifMatch not matching, return 412.");
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }

        // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
        long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
        if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
            logger.debug("ifUnmodifiedSince not matching, return 412.");
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }

        // Prepare and initialize response --------------------------------------------------------
        // Get content type by file name and content disposition.
        String contentType = getServletContext().getMimeType(fileName);
        String disposition = "inline";

        // If content type is unknown, then set the default value.
        // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
        // To add new content types, add new mime-mapping entry in web.xml.
        if (contentType == null) {
            contentType = "application/octet-stream";
        }

        // If content type is text, expand content type with the one and right character encoding.
        if (contentType.startsWith("text")) {
            contentType += ";charset=UTF-8";
        } // Else, expect for images, determine content disposition. If content type is supported by
        // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
        else if (!contentType.startsWith("image")) {
            String accept = request.getHeader("Accept");
            disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
        }

        // Initialize response.
        response.reset();
        response.setBufferSize(bufferSize);
        response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("ETag", eTag);
        response.setDateHeader("Last-Modified", lastModified);
        response.setDateHeader("Expires", expires);

        // Send requested file (part(s)) to client ------------------------------------------------
        // Prepare streams.
        FileInputStream input = null;
        OutputStream output = null;

        if (content) {
            logger.debug("Content requested,streaming.");
            // Open streams.
            input = new FileInputStream(file);
            output = response.getOutputStream();
            long streamed = stream(input, output, bufferSize);
            if (logger.isDebugEnabled()) {
                logger.debug("Bytes streamed:" + streamed);
            }
        }

    }