@param string type (GET/POST/DELETE/PUT)
@param string method 接口名称
@param array params 要传递的参数
@param array headers api请求时的header头信息

@return string
193329
public function request($type, $method, $params, $headers = [], $config = [])
    {
        $response = $this->sendRequest($type, $method, $params, $headers, $config);
        return $response->getBody();
    }
1337586
public static Request create(String method,
                               String url,
                               Map<String, Collection<String>> headers,
                               byte[] body,
                               Charset charset) {
    checkNotNull(method, "httpMethod of %s", method);
    HttpMethod httpMethod = HttpMethod.valueOf(method.toUpperCase());
    return create(httpMethod, url, headers, body, charset);
  }
450851
protected function requestAccessToken($method = 'POST', array $params = array(), $responseType = 'flat')
    {
        $this->log('requestAccessToken()');

        //Set OAuth flow parameters
        if ($this->isOauth1()) {
            //OAuth 1.0
            $this->log('using OAuth1.0a spec');

            $parameters = array('oauth_verifier' => $_GET['oauth_verifier']);
            $parameters = array_merge($parameters, $params);
        } else {
            //OAuth 2.0
            $this->log('using OAuth2 spec');

            $parameters = array(
                'client_id'     => $this->_client_id,
                'redirect_uri'  => $this->_callback,
                'client_secret' => $this->_client_secret,
                'grant_type'    => 'authorization_code'
            );

            if (isset($_GET['code'])) {
                $parameters['code'] = $_GET['code'];
            }

            if (strlen($this->_refresh_token) > 0) {
                $this->log('Using refresh token');
                $parameters['grant_type']    = 'refresh_token';
                $parameters['refresh_token'] = $this->_refresh_token;
            }

            $parameters = array_merge($parameters, $params);
        }

        //Make the request
        $settings = array(
            'responseType'    => $responseType,
            'includeCallback' => true,
            'includeVerifier' => true
        );

        $params = $this->makeRequest($this->_access_token_url, $parameters, $method, $settings);

        //Add the token and secret to session
        if (is_array($params)) {
            if ($this->isOauth1()) {
                //OAuth 1.0a
                if (isset($params['oauth_token']) && isset($params['oauth_token_secret'])) {
                    $this->log('access token set as '.$params['oauth_token']);

                    $this->_access_token         = $params['oauth_token'];
                    $this->_access_token_secret  = $params['oauth_token_secret'];
                    $this->_access_token_updated = true;

                    if ($this->_debug) {
                        $_SESSION['oauth']['debug']['tokens']['access_token']        = $params['oauth_token'];
                        $_SESSION['oauth']['debug']['tokens']['access_token_secret'] = $params['oauth_token_secret'];
                    }

                    return true;
                }
            } else {
                //OAuth 2.0
                if (isset($params['access_token']) && isset($params['expires_in'])) {
                    $this->log('access token set as '.$params['access_token']);

                    $this->_access_token         = $params['access_token'];
                    $this->_expires              = time() + $params['expires_in'];
                    $this->_token_type           = (isset($params['token_type'])) ? $params['token_type'] : null;
                    $this->_refresh_token        = (isset($params['refresh_token'])) ? $params['refresh_token'] : null;
                    $this->_access_token_updated = true;

                    if ($this->_debug) {
                        $_SESSION['oauth']['debug']['tokens']['access_token']  = $params['access_token'];
                        $_SESSION['oauth']['debug']['tokens']['expires_in']    = $params['expires_in'];
                        $_SESSION['oauth']['debug']['tokens']['token_type']    = $params['token_type'];
                        $_SESSION['oauth']['debug']['tokens']['refresh_token'] = $params['refresh_token'];
                    }

                    return true;
                }
            }
        }

        $this->log('response did not have an access token');

        if ($this->_debug) {
            $_SESSION['oauth']['debug']['response'] = $params;
        }

        if (is_array($params)) {
            if (isset($params['errors'])) {
                $errors = array();
                foreach ($params['errors'] as $error) {
                    $errors[] = $error['message'];
                }
                $response = implode("; ", $errors);
            } elseif (isset($params['error'])) {
                // @deprecated support for pre Mautic 2.6.0
                if (is_array($params['error'])) {
                    if (isset($params['error']['message'])) {
                        $response = $params['error']['message'];
                    } else {
                        $response = print_r($params['error'], true);
                    }
                } elseif (isset($params['error_description'])) {
                    $response = $params['error_description'];
                } else {
                    $response = $params['error'];
                }
            } else {
                $response = print_r($params, true);
            }
        } else {
            $response = $params;
        }

        throw new IncorrectParametersReturnedException('Incorrect access token parameters returned: '.$response);
    }
639841
public function request($method, $url, $params = null, $version = null, $headers = null)
    {
        $params = $params ?: [];
        $headers = $headers ?: [];
        if ($this->accessToken && $this->tokenType === 'Bearer') {
            $headers['Authorization'] = 'Bearer ' . $this->accessToken;
        }

        $payloadType = strcasecmp($method, 'get') === 0 ? 'query' : 'json';
        $client = $this->httpClient();

        if (!$this->noVersion) {
            $url = Sumup::getApiVersion() . '/' . $url;
        }

        try {
            $response = $client->request($method, $url, [
                $payloadType => $params,
                'headers' => $headers,
                'http_errors' => false
            ]);
        } catch (\GuzzleHttp\Exception\ClientException $e) {
            throw new Error\ApiRequestorError($e->getMessage());
        }

        return new ApiResponse($response);
    }
1365763
public function call($method, $url, array $post = array(), array $headers = array())
    {
        $options = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => $headers,
        );
        switch ($method) {
            case HttpMethod::GET:
                $options[CURLOPT_POST] = false;
                break;
            case HttpMethod::POST:
                $options[CURLOPT_POST] = true;
                $options[CURLOPT_POSTFIELDS] = json_encode($post);
                break;
            case HttpMethod::PUT:
                $options[CURLOPT_CUSTOMREQUEST] = 'PUT';
                $options[CURLOPT_POSTFIELDS] = json_encode($post);
                break;
            case HttpMethod::DELETE:
                $options[CURLOPT_CUSTOMREQUEST] = 'DELETE';
                $options[CURLOPT_POSTFIELDS] = json_encode($post);
                break;
            default:
                throw new InvalidArgumentException(sprintf('Invalid method: %s', $method));
        }

        $this->curl->init();
        $this->curl->setOptArray($options);
        $rawResponse = $this->curl->exec(1, true);
        $contentType = $this->curl->getInfo(CURLINFO_CONTENT_TYPE);
        if (strpos($contentType, self::CONTENT_TYPE_JSON) === false) {
            return $rawResponse;
        }
        $response = json_decode($rawResponse);
        if (!isset($response->response)) {
            throw new RuntimeException(sprintf('Unexpected response: %s', $rawResponse));
        }
        $response = $response->response;
        if ('OK' == @$response->status) {
            return $response;
        } elseif ('NOAUTH' == @$response->error_id || 'Authentication failed - not logged in' == @$response->error) {
            throw new TokenExpiredException($response);
        }
        throw new ServerException($response);
    }
1170378
protected function getOAuthHeader($method, $url, $params = [], $multipart = false)
    {
        $oauth['oauth_consumer_key']     = $this->consumerKey;
        $oauth['oauth_nonce']            = time();
        $oauth['oauth_signature_method'] = self::OAUTH_SIGNATURE_METHOD;
        $oauth['oauth_timestamp']        = time();
        $oauth['oauth_token']            = $this->token;
        $oauth['oauth_version']          = self::OAUTH_VERSION;

        if (!$multipart) {
            $signParams = array_merge($params, $oauth);
        } else {
            $signParams = $oauth;
        }

        uksort($signParams, 'strcmp');

        $query = $this->encodeParams($signParams);

        $queryString = implode('&', $query);

        $signature = strtoupper($method)
            . '&' . $this->urlencodeRfc3986($url)
            . '&' . $this->urlencodeRfc3986($queryString);

        $signingKey = $this->urlencodeRfc3986($this->consumerSecret)
            . '&' . $this->urlencodeRfc3986($this->tokenSecret);

        $hash_hmac = hash_hmac('sha1', $signature, $signingKey, true);
        $oauth['oauth_signature'] = base64_encode($hash_hmac);

        uksort($oauth, 'strcmp');
        $authParams = $this->encodeParams($oauth, true);

        return 'OAuth ' . implode(', ', $authParams);
    }
264016
protected function configureHTTPMethod($method) {
        switch($method){
            case self::HTTP_GET:
                $this->removeHeader('Content-Type');
                break;
            case self::HTTP_POST:
            case self::HTTP_PUT:
                $this->addHeader("Content-Type", "multipart/form-data");
        }
        return parent::configureHTTPMethod($method);
    }
1006768
public void doGeneric(String method, HttpServletRequest request, HttpServletResponse response) {
    try {
      ServletUtils.startTransaction(request.getHeader("User-Agent"));

      // Note that getServletPath does an un-escape so that the %24 of job id's are turned into $ characters.
      String uri = request.getServletPath();

      Properties headers = new Properties();
      Enumeration<String> en = request.getHeaderNames();
      while (en.hasMoreElements()) {
        String key = en.nextElement();
        String value = request.getHeader(key);
        headers.put(key, value);
      }

      final String contentType = request.getContentType();
      Properties parms = new Properties();
      String postBody = null;
      if (System.getProperty(H2O.OptArgs.SYSTEM_PROP_PREFIX + "debug.cors") != null) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
      }

      if (contentType != null && contentType.startsWith(MIME_JSON)) {
        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
          BufferedReader reader = request.getReader();
          while ((line = reader.readLine()) != null)
            jb.append(line);
        } catch (Exception e) {
          throw new H2OIllegalArgumentException("Exception reading POST body JSON for URL: " + uri);
        }
        postBody = jb.toString();
      } else {
        // application/x-www-form-urlencoded
        Map<String, String[]> parameterMap;
        parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
          String key = entry.getKey();
          String[] values = entry.getValue();

          if (values.length == 1) {
            parms.put(key, values[0]);
          } else if (values.length > 1) {
            StringBuilder sb = new StringBuilder();
            sb.append("[");
            boolean first = true;
            for (String value : values) {
              if (!first) sb.append(",");
              sb.append("\"").append(value).append("\"");
              first = false;
            }
            sb.append("]");
            parms.put(key, sb.toString());
          }
        }
      }

      // Make serve() call.
      NanoResponse resp = serve(uri, method, headers, parms, postBody);

      // Un-marshal Nano response back to Jetty.
      String choppedNanoStatus = resp.status.substring(0, 3);
      assert (choppedNanoStatus.length() == 3);
      int sc = Integer.parseInt(choppedNanoStatus);
      ServletUtils.setResponseStatus(response, sc);

      response.setContentType(resp.mimeType);

      Properties header = resp.header;
      Enumeration<Object> en2 = header.keys();
      while (en2.hasMoreElements()) {
        String key = (String) en2.nextElement();
        String value = header.getProperty(key);
        response.setHeader(key, value);
      }

      resp.writeTo(response.getOutputStream());

    } catch (IOException e) {
      e.printStackTrace();
      ServletUtils.setResponseStatus(response, 500);
      Log.err(e);
      // Trying to send an error message or stack trace will produce another IOException...
    } finally {
      ServletUtils.logRequest(method, request, response);
      // Handle shutdown if it was requested.
      if (H2O.getShutdownRequested()) {
        (new Thread() {
          public void run() {
            boolean [] confirmations = new boolean[H2O.CLOUD.size()];
            if (H2O.SELF.index() >= 0) {
              confirmations[H2O.SELF.index()] = true;
            }
            for(H2ONode n:H2O.CLOUD._memary) {
              if(n != H2O.SELF)
                new RPC<>(n, new UDPRebooted.ShutdownTsk(H2O.SELF,n.index(), 1000, confirmations, 0)).call();
            }
            try { Thread.sleep(2000); }
            catch (Exception ignore) {}
            int failedToShutdown = 0;
            // shutdown failed
            for(boolean b:confirmations)
              if(!b) failedToShutdown++;
            Log.info("Orderly shutdown: " + (failedToShutdown > 0? failedToShutdown + " nodes failed to shut down! ":"") + " Shutting down now.");
            H2O.closeAll();
            H2O.exit(failedToShutdown);
          }
        }).start();
      }
      ServletUtils.endTransaction();
    }
  }
105609
public static String getHeaders(HttpMethod method) {
        String headerString = "";
        Header[] headers = method.getRequestHeaders();
        for (Header header : headers) {
            String name = header.getName();
            if (name.equals(Constants.ODO_PROXY_HEADER)) {
                // skip.. don't want to log this
                continue;
            }

            if (headerString.length() != 0) {
                headerString += "\n";
            }

            headerString += header.getName() + ": " + header.getValue();
        }

        return headerString;
    }
394411
function(method, data, callback) {
      xhr.open(method, url, true, user, password);
      if (mimeType != null && !headers.has("accept")) headers.set("accept", mimeType + ",*/*");
      if (xhr.setRequestHeader) headers.each(function(value, name) { xhr.setRequestHeader(name, value); });
      if (mimeType != null && xhr.overrideMimeType) xhr.overrideMimeType(mimeType);
      if (responseType != null) xhr.responseType = responseType;
      if (timeout > 0) xhr.timeout = timeout;
      if (callback == null && typeof data === "function") callback = data, data = null;
      if (callback != null && callback.length === 1) callback = fixCallback(callback);
      if (callback != null) request.on("error", callback).on("load", function(xhr) { callback(null, xhr); });
      event.call("beforesend", request, xhr);
      xhr.send(data == null ? null : data);
      return request;
    }
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;
  }
1229907
public function getSignature($params = [], $method = Alidayu::SIGN_METHOD_HMAC)
    {
        $rawQuery = [];
        ksort($params);
        foreach ($params as $k => $v) {
            $rawQuery[] = sprintf('%s%s', $k, $v);
        }
        $rawText = implode('', $rawQuery);
        $signature = '';
        if ($method === Alidayu::SIGN_METHOD_MD5) {
            $signature = md5($this->appSecret . $rawText . $this->appSecret);
        } elseif ($method === Alidayu::SIGN_METHOD_HMAC) {
            $signature = hash_hmac('md5', $rawText, $this->appSecret);
        }
        return strtoupper($signature);
    }
972206
public function request($method, $path, $query, $body = [], $type = 'json')
    {
        // reset errors
        $this->errorMessages = [];

        $query['wt'] = 'json';
        $request = [
            'Accept' => 'application/json',
            'query' => $query
        ];

        if ($method != 'GET') {
            $request[$type] = $body;
        }

        try {
            $res = $this->client->request($method, $path, $request);

            return json_decode($res->getBody()->getContents(), true);
        } catch (RequestException $e) {
            if ($e->getResponse() === null) {
                $this->logError($e->getMessage());

                return false;
            }

            // 4xx
            if ($e->getResponse()->getStatusCode() == 400) {
                $content = $e->getResponse()->getBody()->getContents();
                $this->logError($content);

                return json_decode($content, true);
            }

            if ($e->getResponse()->getStatusCode() === 404) {
                $this->logError('404. Path: '.$e->getRequest()->getUri()->getPath(). " doesn't exist");

                return false;
            }

            $this->logError($e->getMessage());

            return false;
        }
    }
1050067
public function createRequest($method, $uri, array $headers = [], $body = null, $protocol = '1.1')
    {
        if (is_array($body)) {
            $body = http_build_query($body, '', '&');
        }

        if ($method == 'GET') {
            $uri .= ((strpos('?', $uri) === false) ? '?' : '&').$body;
            $body = '';
        }

        return $this->requestFactory->createRequest($method, $uri, $headers, $body, $protocol);
    }
1277362
private function privateRequest($url, $params = [], $method = 'GET')
    {
        // build the POST data string
        $params['timestamp']  = number_format((microtime(true) * 1000), 0, '.', '');
        $params['recvWindow'] = $this->recvWindow;

        $query   = http_build_query($params, '', '&');

        // set API key and sign the message
        $sign    = hash_hmac('sha256', $query, $this->secret);

        $headers = array(
            'X-MBX-APIKEY: ' . $this->key
        );

        // make request
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $headers);
   
         // build the POST data string
        $postdata = $params;

        // Set URL & Header
        curl_setopt($this->curl, CURLOPT_URL, $this->url . $url."?{$query}&signature={$sign}");

        //Add post vars
        if($method == "POST") {
            curl_setopt($this->curl,CURLOPT_POST, 1);
            curl_setopt($this->curl, CURLOPT_POSTFIELDS, array());
        }

        //Get result
        $result = curl_exec($this->curl);
        if($result === false)
            throw new \Exception('CURL error: ' . curl_error($this->curl));

         // decode results
        $result = json_decode($result, true);
        if(!is_array($result) || json_last_error())
            throw new \Exception('JSON decode error');

        return $result;

    }
717272
protected function request($method, $url, $parameters = array())
    {
        Logger::get()->debug('HTTP: starting request...');
        $headers = $this->headers;

        // Add accepted content type header.
        $headers[] = 'Content-Type: ' . $this->contentType;
        $headers[] = 'Accept: ' . $this->acceptedContentType;

        $handler = curl_init();

        if (!is_null($this->user)) {
            curl_setopt($handler, CURLOPT_USERPWD, $this->user . ':' . $this->password);
        }

        Logger::get()->debug('HTTP: method is ' . $method);
        switch ($method) {
            case self::METHOD_DELETE:
                curl_setopt($handler, CURLOPT_URL, $url . '?' . http_build_query($parameters));
                curl_setopt($handler, CURLOPT_CUSTOMREQUEST, self::DELETE);
                break;
            case self::METHOD_POST:
                curl_setopt($handler, CURLOPT_URL, $url);
                curl_setopt($handler, CURLOPT_POST, true);
                curl_setopt($handler, CURLOPT_POSTFIELDS, $parameters);
                break;
            case self::METHOD_GET:
                curl_setopt($handler, CURLOPT_URL, $url . '?' . http_build_query($parameters));
                break;
        }

        curl_setopt($handler, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($handler, CURLOPT_HTTPHEADER, $headers);
        Logger::get()->debug('HTTP: headers set.');

        // Send the request to the server.
        Logger::get()->debug("HTTP: requesting $url...");
        $output = curl_exec($handler);
        $errNo = curl_errno($handler);
        $error = curl_error($handler);
        // Obtain the status.
        Logger::get()->debug('HTTP: Done. Getting status...');
        $status = curl_getinfo($handler, CURLINFO_HTTP_CODE);
        // The handler is no longer needed.
        curl_close($handler);
        Logger::get()->debug('HTTP: request finished.');

        if ($errNo) {
            throw new Exception('HTTP: cURL failed: ' . $error, $errNo);
        }

        // If cURL had no errors itself, then there is an HTTP response.
        switch ($status) {
            case self::STATUS_OK:
            case self::STATUS_CREATED:
            case self::STATUS_ACCEPTED:
            case self::STATUS_NO_CONTENT:
                return $output;
            default:
                throw new Http\Exception("HTTP {$status}", $status);
        }
    }
122721
public function request($method, $url, $params = null, $headers = [])
    {
        $headers = array_merge(self::defaultHeaders(), $headers);
        $absUrl = $this->apiBase . $url;
        return $this->httpClient()->request($method, $absUrl, $params, $headers);
    }