Helper method to build the request to the server.

@param path the path.
@param method the method.
@param params the json string.
@return the request.
962825
protected HttpUriRequest setupRequestJson(final String path, final String method, final String params) {
        final HttpUriRequest request = buildMethod(method, path, params);
        request.addHeader(new BasicHeader("Accept", "application/json"));
        request.addHeader(new BasicHeader("Accept-Charset", "utf-8"));
        request.setHeader(new BasicHeader("Authorization", "Basic " + new String(Base64.encodeBase64((this.token + ":" + this.secret).getBytes()))));
        return request;
    }
1040304
function (params, method) {
        var that = this,
            request = $.ajax(
                that.getAjaxParams(method, { data: utils.serialize(params) })
            );

        that.abortRequest();
        that.currentRequest = request;
        that.notify('request');

        request.always(function () {
            that.currentRequest = null;
            that.notify('request');
        });

        return request;
    }
413296
private function request(string $method, string $path, array $query = [], $body = null): string
    {
        // Prepare request:
        $query = build_query($query);
        $body = $this->parseBody($body);
        $path = trim($path, '/');
        $request = new Request(
            $method,
            "{$this->baseUri}/v3/$path/?$query",
            ['Content-Type' => 'application/json'],
            $body
        );

        return (string) $this->query($request)->getBody();
    }
409864
public Object invokeMethod(String method, Object[] params) {
        log.debug("invokeMethod url: {}", (url + appendToUrl));
        IoBuffer resultBuffer = null;
        IoBuffer data = encodeInvoke(method, params);
        //setup POST
        HttpPost post = null;
        try {
            post = new HttpPost(url + appendToUrl);
            post.addHeader("Content-Type", CONTENT_TYPE);
            post.setEntity(new InputStreamEntity(data.asInputStream(), data.limit()));
            // execute the method
            HttpResponse response = client.execute(post);
            int code = response.getStatusLine().getStatusCode();
            log.debug("HTTP response code: {}", code);
            if (code / 100 != 2) {
                throw new RuntimeException("Didn't receive success from remoting server");
            } else {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    //fix for Trac #676
                    int contentLength = (int) entity.getContentLength();
                    //default the content length to 16 if post doesn't contain a good value
                    if (contentLength < 1) {
                        contentLength = 16;
                    }
                    // get the response as bytes
                    byte[] bytes = EntityUtils.toByteArray(entity);
                    resultBuffer = IoBuffer.wrap(bytes);
                    Object result = decodeResult(resultBuffer);
                    if (result instanceof RecordSet) {
                        // Make sure we can retrieve paged results
                        ((RecordSet) result).setRemotingClient(this);
                    }
                    return result;
                }
            }
        } catch (Exception ex) {
            log.error("Error while invoking remoting method: {}", method, ex);
            post.abort();
        } finally {
            if (resultBuffer != null) {
                resultBuffer.free();
                resultBuffer = null;
            }
            data.free();
            data = null;
        }
        return null;
    }
1078460
public function request($method, $path = null, $parameters = array())
    {
        if (null === $path) {
            $url = '/messages';
        } else {
            $url  = '/messages/'.$path;
        }

        return json_decode($this->requestRaw($method, $url, $parameters), true);
    }
1229471
public String path(M method, T target, Object... params) {
    MethodlessRouter<T> router = (method == null)? anyMethodRouter : routers.get(method);
    if (router == null) router = anyMethodRouter;

    String ret = router.path(target, params);
    if (ret != null) return ret;

    return (router == anyMethodRouter)? null : anyMethodRouter.path(target, params);
  }
921149
function makeRequest (path, params) {
    // The api key will always be sent as a query parameter
    params = params || {}
    params.token = apiKey

    return new Promise(function (resolve, reject) {
      request(`${hostname}${path}?${querystring.stringify(params)}`,
        function (error, response, body) {
          if (error) {
            reject(error)
          }
          try {
            var result = JSON.parse(body)
            if (response.statusCode === 200) {
              resolve(result)
            }
            reject(result.error)
          } catch (error) {
            reject(response.statusMessage)
          }
        })
    })
  }
1370117
protected function buildRequests($method, $urls, $params = [])
    {
        $reqs = [];
        foreach ($urls as $key => $url) {
            $reqs[$key] = $this->buildRequest($method, $url, $params);
        }
        return $reqs;
    }
911436
def request(method, action, params={}, options={})
      # Augment in interesting options
      options[:call_chain] = _path_array
      options[:action] = action
      @requester.send(method, _path(action), params, options)
    end
276661
public function build($method, $uri, $params = null)
	{
		$request = [
			'http_method' => $method,
			'scheme' => $this->schema,
			'uri' => $this->uri . $uri,
			'headers' => [
				'Host' => [$this->host],
				'User-Agent' => [$this->getUserAgent()],
			],
			'client' => [
				'connect_timeout' => 30,
				'timeout' => 60,
			],
			'version' => 1.1,
		];

		// Build query
		if (!empty($params)) {
			$request['query_string'] = http_build_query($params);
		}

		return $request;
	}
911884
protected function buildRequest($method, $url, $params = [])
    {
        if (count($params) > 0) {
            $url .= strpos($url, '?') === false ? '?' : '&';
            $url .= http_build_query($params);
        }
        return new Request($url, $method);
    }
3730
private function _call($method, $path, $param, $header = false) {
    // Clear connection; Set timeout, and json header.
    $this->curl->resetConnection();

    // Set additional headers.
    if ($header) {
      foreach ($header as $name => $value) {
        $this->curl->setHeader($name, $value);
      }
    }

    // Make an API request to the GDAX server.
    if ($param) {
      // If the method is not GET, pass JSON in the request body.
      $payload = false;
      if ($method != 'GET') {
        $param = json_encode($param);
        $payload = true;
      }
      $this->curl->{strtolower($method)}("$this->api/$path", $param, $payload);
    } else {
      $this->curl->{strtolower($method)}("$this->api/$path");
    }

    // TODO: Move error logs out of class. ~: Monolog
    // Error Logging
    if ($this->curl->error) {
      $this->_error[] = "$path: {$this->curl->error_message}";
      if ($this->_debug) {
        $this->_error[] = $this->_dump($path, $param);
      }
    }

    if (is_null($ret = json_decode($this->curl->response))) {
      throw new \Exception(__METHOD__ ." - Invalid JSON or null returned."); 
    }

    // Throw an exception on any returned messages from GDAX.
    if ($ret && isset($ret->message)) {
      throw new \Exception("API: $path-> ". $ret->message);
    }

    return $ret;
  }
853020
def make_request(self, path, params=None, data=None, method=None):
        '''
        
        '''
        # Setup values
        url = self.build_url(path, params)
        client_log.debug('Requesting:  %s' % url)
        method = method or 'GET'
        body = None
        headers = {}

        if data:
            method = 'POST'
            body = urlencode(data)
            headers = {
                'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
            }

        client_log.debug('Request Method:  %s' % method)
        client_log.debug('Request Body(Data):  %s' % data)
        client_log.debug('Request Body(Raw):  %s' % body)

        # Setup http client
        h = httplib2.Http(cache=self.cache, timeout=self.timeout)
        #h.add_credentials(self.username, self.password)
        # Skip the normal http client behavior and send auth headers immediately
        # to save an http request.
        headers['Authorization'] = "Basic %s" % base64.standard_b64encode(self.username + ':' + self.password).strip()

        # Make request
        response, content = h.request(url, method, body=body, headers=headers)
        status = response.status
        client_log.debug('Response Status:  %d' % status)
        client_log.debug('Response Content:  %s' % content)
        if status != 200 and status != 302:
            exception_class = CheddarError
            if status == 401:
                exception_class = AccessDenied
            elif status == 400:
                exception_class = BadRequest
            elif status == 404:
                exception_class = NotFound
            elif status == 412:
                exception_class = PreconditionFailed
            elif status == 500:
                exception_class = CheddarFailure
            elif status == 502:
                exception_class = NaughtyGateway
            elif status == 422:
                exception_class = UnprocessableEntity

            raise exception_class(response, content)

        response.content = content
        return response
1252433
protected function performRequest($method, $path, array $params)
	{
		/* Combine given parameters with persistent parameters and convert to string values. */
		$params = array_map('strval', $params + $this->persistent_params);

		$params = $this->signRequest($path, $params, $this->getAppSecret());
		$result = $this->doRequest($method, $path, $params);

		$this->logRequest($method, $path, $params, $result);

        /* See if there were cURL errors */
        if (empty($result["body"])) {
            throw new Mollie_Exception($result["message"], $result["code"]);
        }
        $object = $this->convertResponseBodyToObject($result['body'], $result['content_type']);

        if ($object instanceof Mollie_Response) {
            $this->checkResultErrors($object);
        }

        return $object;
    }
854495
def request(http_method, path, params)
      response = connection.send(http_method, path, params)
      response.body
    end
1016212
protected function _restserver($path, $method = 'GET', $params = array(), $getParams = array()) {
        $this->container = null;
        if ($this->debug) { $start = microtime(true); }
        if (is_array($method) && empty($params)) {
            $params = $method;
            $method = 'GET';
        }
        $getParams['method'] = $method; // method override as we always do a POST
        $uri = $this->getUrl('api', $path);
        $result = $this->_oauthRequest($uri, $params, $getParams);

        if (floatval($this->api_version) >= 2) {
            $container = json_decode($result, true);
            if ($container && array_key_exists('name', $container) && $container['name'] == 'SPP Container') {
                $this->container = $container;
            }
        }

        preg_match("/\.(json|jsonp|html|xml|serialize|php|csv|tgz)$/", $path, $matches);
        if ($matches) {
            switch ($matches[1]) {
                case 'json':
                    $result = json_decode($result, true);
                    break;
                default:
                    if ($this->debug) { $this->timer[__FUNCTION__]['elapsed'][] = microtime(true)-$start; }
                    return $result;
                    break;
            }
        } else
            $result = json_decode($result, true);

        // results are returned, errors are thrown
        if (is_array($result) && isset($result['error']) && $result['error']) {
            $e = new VGS_Client_Exception($result, $this->raw);
            switch ($e->getType()) {
                case 'ApiException':
                    break;
                // OAuth 2.0 Draft 00 style
                case 'OAuthException':
                    // OAuth 2.0 Draft 10 style
                case 'invalid_token':
                    $this->setSession(null);
            }
            throw $e;
        }
        if (floatval($this->api_version) >= 2 && $result && is_array($result) && array_key_exists('name', $result) && $result['name'] == 'SPP Container') {
            if (isset($result['sig']) && isset($result['algorithm'])) {
                $result = $this->validateAndDecodeSignedRequest($result['sig'], $result['data'], $result['algorithm']);
            } else {
                $result = $result['data'];
            }
        }
        if ($this->debug) { $this->timer[__FUNCTION__]['elapsed'][] = microtime(true)-$start; }
        return $result;
    }
1350100
def _build_request(self, method, url, params=None):
        
        full_params = self._get_base_params()
        if params is not None:
            full_params.update(params)
        try:
            request_func = lambda u, d: \
                getattr(self._connector, method.lower())(u, params=d,
                    headers=self._request_headers)
        except AttributeError:
            raise ApiException('Invalid request method')
        # TODO: need to catch a network here and raise as ApiNetworkException

        def do_request():
            logger.debug('Sending %s request "%s" with params: %r',
                method, url, full_params)
            try:
                resp = request_func(url, full_params)
                logger.debug('Received response code: %d', resp.status_code)
            except requests.RequestException as err:
                raise ApiNetworkException(err)

            try:
                resp_json = resp.json()
            except TypeError:
                resp_json = resp.json

            method_returns_list = False
            try:
                resp_json['error']
            except TypeError:
                logger.warn('Api method did not return map: %s', method)
                method_returns_list = True
            except KeyError:
                logger.warn('Api method did not return map with error key: %s', method)

            if method_returns_list is None:
                raise ApiBadResponseException(resp.content)
            elif method_returns_list:
                data = resp_json
            else:
                try:
                    if resp_json['error']:
                        raise ApiError('%s: %s' % (resp_json['code'], resp_json['message']))
                except KeyError:
                    data = resp_json
                else:
                    data = resp_json['data']
                    self._do_post_request_tasks(data)
            self._last_response = resp
            return data
        return do_request