Apply POST fields and files to a request to attempt to give an accurate
representation.

@param RequestInterface $request Request to update
@param array            $body    Body to apply
321807
protected function addPostData(RequestInterface $request, array $body)
    {
        static $fields = ['string' => true, 'array' => true, 'NULL' => true,
            'boolean' => true, 'double' => true, 'integer' => true];

        $post = new PostBody();
        foreach ($body as $key => $value) {
            if (isset($fields[gettype($value)])) {
                $post->setField($key, $value);
            } elseif ($value instanceof PostFileInterface) {
                $post->addFile($value);
            } else {
                $post->addFile(new PostFile($key, $value));
            }
        }

        if ($request->getHeader('Content-Type') == 'multipart/form-data') {
            $post->forceMultipartUpload(true);
        }

        $request->setBody($post);
    }
530295
protected function preparePostRequest(RequestInterface $request, $data)
    {
        if ($data !== null) {
            // Add the POST data to the request.
            $request->setOption(CURLOPT_POST, true);
            $request->setOption(CURLOPT_POSTFIELDS, $data);
        } else {
            $request->setOption(CURLOPT_CUSTOMREQUEST, 'POST');
        }
    }
1294042
public function submit(RequestInterface $request)
    {
        $response = $this->browser->submit(
            $this->options['host'] . $request->getPath(),
            $request->getData(),
            $request->getMethod());

        return json_decode($response->getContent());
    }
1322304
public function bindRequest(Request $request)
    {
        $this->request = $request;

        foreach ($this->request->postArray() as $key => $value) {
            if (isset($this->fieldSet[$key])) {
                $this->fieldSet[$key]->setValue($value);
            }
        }
    }
1242200
private function onBefore(RequestInterface $request)
    {
        $headers = $request->getHeaders();

        //prepare Header
        $headers["Date"] = gmdate($this->config['dateTimeFormat']);
        $headers["Accept"] = 'application/octet-stream';
        $headers["x-acs-signature-method"] = $this->config['signatureMethod'];
        $headers["x-acs-signature-version"] = $this->config['signatureVersion'];
        $headers['x-acs-version'] = $this->config['Version'];

        if (isset($this->config['regionId'])) {
            $headers["x-acs-region-id"] = $this->config['regionId'];
        }

        $content = $request->getBody()->getContents();
        if ($content != null) {
            $headers["Content-MD5"] = base64_encode(md5(json_encode($content), true));
        }
        $headers["Content-Type"] = "application/octet-stream;charset=utf-8";

        //compose Url

        $signString = $request->getMethod() . self::$headerSeparator;
        if (isset($headers["Accept"])) {
            $signString = $signString . $headers["Accept"];
        }
        $signString = $signString . self::$headerSeparator;

        if (isset($headers["Content-MD5"])) {
            $signString = $signString . $headers["Content-MD5"];
        }
        $signString = $signString . self::$headerSeparator;

        if (isset($headers["Content-Type"])) {
            $signString = $signString . $headers["Content-Type"];
        }
        $signString = $signString . self::$headerSeparator;

        if (isset($headers["Date"])) {
            $signString = $signString . $headers["Date"];
        }
        $signString = $signString . self::$headerSeparator;

        $params = \GuzzleHttp\Psr7\parse_query($request->getUri()->getQuery());
        $signString = $signString . $this->buildCanonicalHeaders($headers);
        ksort($params);//参数排序
        $query = \GuzzleHttp\Psr7\build_query($params);
        $signString .= $query;

        $headers["Authorization"] = "acs " . $this->config['accessKeyId'] . ":"
            . base64_encode(hash_hmac('sha1', $signString, $this->config['accessSecret'], true));

        /** @var RequestInterface $request */
        $request = $request->withUri($request->getUri()->withQuery($query));
        foreach ($headers as $name => $val) {
            $request->withHeader($name, $val);
        }
        return $request;
    }
585036
protected function setBody(StreamInterface $body)
    {
        if ($body instanceof OutputBufferStream && $this->isStale() === false) {
            $body->useGlobally();
        }
        
        $this->body = $body;
    }
132060
private function addRequestBodyOptions(RequestInterface $request, array $curlOptions): array
    {
        /*
         * Some HTTP methods cannot have payload:
         *
         * - GET — cURL will automatically change method to PUT or POST if we set CURLOPT_UPLOAD or
         *   CURLOPT_POSTFIELDS.
         * - HEAD — cURL treats HEAD as GET request with a same restrictions.
         * - TRACE — According to RFC7231: a client MUST NOT send a message body in a TRACE request.
         */
        if (!in_array($request->getMethod(), ['GET', 'HEAD', 'TRACE'], true)) {
            $body = $request->getBody();
            $bodySize = $body->getSize();
            if ($bodySize !== 0) {
                if ($body->isSeekable()) {
                    $body->rewind();
                }

                // Message has non empty body.
                if (null === $bodySize || $bodySize > 1024 * 1024) {
                    // Avoid full loading large or unknown size body into memory
                    $curlOptions[CURLOPT_UPLOAD] = true;
                    if (null !== $bodySize) {
                        $curlOptions[CURLOPT_INFILESIZE] = $bodySize;
                    }
                    $curlOptions[CURLOPT_READFUNCTION] = function ($ch, $fd, $length) use ($body) {
                        return $body->read($length);
                    };
                } else {
                    // Small body can be loaded into memory
                    $curlOptions[CURLOPT_POSTFIELDS] = (string)$body;
                }
            }
        }

        if ($request->getMethod() === 'HEAD') {
            // This will set HTTP method to "HEAD".
            $curlOptions[CURLOPT_NOBODY] = true;
        } elseif ($request->getMethod() !== 'GET') {
            // GET is a default method. Other methods should be specified explicitly.
            $curlOptions[CURLOPT_CUSTOMREQUEST] = $request->getMethod();
        }

        return $curlOptions;
    }
1371934
private function createRequest(RequestInterface $request)
    {
        $options = [
            'exceptions' => false,
            'allow_redirects' => false,
        ];

        $options['version'] = $request->getProtocolVersion();
        $options['headers'] = $request->getHeaders();
        $body = (string) $request->getBody();
        $options['body'] = '' === $body ? null : $body;

        return $this->client->createRequest(
            $request->getMethod(),
            (string) $request->getUri(),
            $options
        );
    }
204282
function parseBody(Swoole\Request $request)
    {
        $cd = strstr($request->header['Content-Type'], 'boundary');
        if (isset($request->header['Content-Type']) and $cd !== false)
        {
            $this->parseFormData($request, $cd);
        }
        else
        {
            if (substr($request->header['Content-Type'], 0, 33) == 'application/x-www-form-urlencoded')
            {
                parse_str($request->body, $request->post);
            }
        }
    }
1301518
private function validateBody($body, $requestHeaders)
    {
        $signature = $this->getHeaderValue($requestHeaders, 'X-GCS-Signature');
        $keyId = $this->getHeaderValue($requestHeaders, 'X-GCS-KeyId');
        $secretKey = $this->secretKeyStore->getSecretKey($keyId);

        $expectedSignature = base64_encode(hash_hmac("sha256", $body, $secretKey, true));

        $isValid = $this->areEqualSignatures($signature, $expectedSignature);
        if (!$isValid) {
            throw new SignatureValidationException("failed to validate signature '$signature'");
        }
    }
1299228
public function setRequest(RequestInterface $request)
    {
        $this->setParam('request', $request);
        $this->request = $request;

        return $this;
    }
1245240
private function buildRequestBody(RequestInterface $request, array $payload)
    {
        $hasFiles = false;
        foreach ($payload as $value) {
            if ($value instanceof File) {
                $hasFiles = true;
                break;
            }
        }

        if ($hasFiles) {
            $builder = $this->getMultipartStreamBuilder();
            foreach ($payload as $key => $value) {
                if ($value instanceof File) {
                    $builder->addResource(
                        $key,
                        $value->getResource(),
                        ['filename' => $value->getFilename()]
                    );
                } else {
                    $builder->addResource($key, $value);
                }
            }

            try {
                $request = $request
                    ->withHeader(
                        'Content-type',
                        'multipart/form-data; boundary=' . $builder->getBoundary()
                    )
                    ->withBody($builder->build());
            } catch (\Exception $e) {
                throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
            }
        } else {
            try {
                $request = $request
                    ->withHeader('Content-type', 'application/json')
                    ->withBody($this->streamFactory->createStream(json_encode($payload)));
            } catch (\Exception $e) {
                throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
            }
        }

        return $request;
    }
820904
public function setBody($body, $content_type = false){
	
		// clear old body data
		$this->post->clear();
		$this->files->clear();
		
		// is this form data?
		if(is_array($body)){
			$body = http_build_query($body);
		}
		
		$this->body = (string)$body;
		
		// plain text should be: text/plain; charset=UTF-8
		if($content_type){
			$this->headers->set('content-type', $content_type);
		}
		
		// do it!
		$this->prepare();
	}
439478
private function applyOptions(RequestInterface $request, array &$options)
    {
        $modify = [];

        if (isset($options['form_params'])) {
            if (isset($options['multipart'])) {
                throw new InvalidBodySourceException();
            }
            $options['body'] = http_build_query($options['form_params'], null, '&');
            unset($options['form_params']);
            $options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded';
        }

        if (isset($options['multipart'])) {
            $elements = $options['multipart'];
            unset($options['multipart']);
            $options['body'] = new Psr7\MultipartStream($elements);
        }

        if (!empty($options['decode_content'])
            && $options['decode_content'] !== true
        ) {
            $modify['set_headers']['Accept-Encoding'] = $options['decode_content'];
        }

        if (isset($options['headers'])) {
            if (isset($modify['set_headers'])) {
                $modify['set_headers'] = $options['headers'] + $modify['set_headers'];
            } else {
                $modify['set_headers'] = $options['headers'];
            }
            unset($options['headers']);
        }

        if (isset($options['body'])) {
            if (is_array($options['body'])) {
                throw new InvalidBodyException();
            }
            $modify['body'] = Psr7\stream_for($options['body']);
            unset($options['body']);
        }

        if (!empty($options['auth'])) {
            $value = $options['auth'];
            $type = is_array($value)
                ? (isset($value[2]) ? strtolower($value[2]) : 'basic')
                : $value;
            $config['auth'] = $value;
            switch (strtolower($type)) {
                case 'basic':
                    $modify['set_headers']['Authorization'] = 'Basic '
                        . base64_encode("$value[0]:$value[1]");
                    break;
                case 'digest':
                    // @todo: Do not rely on curl
                    $options['curl'][CURLOPT_HTTPAUTH] = CURLAUTH_DIGEST;
                    $options['curl'][CURLOPT_USERPWD] = "$value[0]:$value[1]";
                    break;
            }
        }

        if (isset($options['query'])) {
            $value = $options['query'];
            if (is_array($value)) {
                $value = http_build_query($value, null, '&', PHP_QUERY_RFC3986);
            }
            if (!is_string($value)) {
                throw new InvalidQueryException();
            }
            $modify['query'] = $value;
            unset($options['query']);
        }

        if (isset($options['json'])) {
            $modify['body'] = Psr7\stream_for(json_encode($options['json']));
            $options['_conditional']['Content-Type'] = 'application/json';
            unset($options['json']);
        }

        $request = Psr7\modify_request($request, $modify);

        if ($request->getBody() instanceof Psr7\MultipartStream) {
            // Use a multipart/form-data POST if a Content-Type is not set.
            $options['_conditional']['Content-Type'] = 'multipart/form-data; boundary='
                . $request->getBody()->getBoundary();
        }

        // Merge in conditional headers if they are not present.
        if (isset($options['_conditional'])) {
            // Build up the changes so it's in a single clone of the message.
            $modify = [];
            foreach ($options['_conditional'] as $k => $v) {
                if (!$request->hasHeader($k)) {
                    $modify['set_headers'][$k] = $v;
                }
            }
            $request = Psr7\modify_request($request, $modify);
            // Don't pass this internal value along to middleware/handlers.
            unset($options['_conditional']);
        }

        return $request;
    }
69287
private function appendHeaders(RequestInterface $request)
    {
        $headers = $this->auth->getHeaders();
        foreach ($headers as $key => $value) {
            $request = $request->withHeader($key, $value);
        }
        return $request;
    }
513262
function request($method, $body = NULL, $header = array()){
        foreach($body as $key => $val) {
            if($val === null) {
                unset($body[$key]);
            }
        }

        ShortPixel::log("REQUEST BODY: " . json_encode($body));

        $retUrls = array("body" => array(), "headers" => array(), "fileMappings" => array());
        $retPend = array("body" => array(), "headers" => array(), "fileMappings" => array());
        $retFiles = array("body" => array(), "headers" => array(), "fileMappings" => array());

        if(isset($body["urllist"])) {
            $retUrls = $this->requestInternal($method, $body, $header);
        }
        if(isset($body["pendingURLs"])) {
            unset($body["urllist"]);
            //some files might have already been processed as relaunches in the given max time
            foreach($retUrls["body"] as $url) {
                //first remove it from the files list as the file was uploaded properly
                if($url->Status->Code != -102 && $url->Status->Code != -106) {
                    $notExpired[] = $url;
                    if(!isset($body["pendingURLs"][$url->OriginalURL])) {
                        $lala = "cucu";
                    } else
                    $unsetPath = $body["pendingURLs"][$url->OriginalURL];
                    if(isset($body["files"]) && ($key = array_search($unsetPath, $body["files"])) !== false) {
                        unset($body["files"][$key]);
                    }
                }
                //now from the pendingURLs if we already have an answer with urllist
                if(isset($body["pendingURLs"][$url->OriginalURL])) {
                    $retUrls["fileMappings"][$url->OriginalURL] = $body["pendingURLs"][$url->OriginalURL];
                    unset($body["pendingURLs"][$url->OriginalURL]);
                }
            }
            if(count($body["pendingURLs"])) {
                $retPend = $this->requestInternal($method, $body, $header);
                if(isset($retPend['body']->Status->Code) && $retPend['body']->Status->Code < 0) { //something's wrong (API key?)
                    throw new ClientException($retPend['body']->Status->Message, $retPend['body']->Status->Code);

                }
                if(isset($body["files"])) {
                    $notExpired = array();
                    foreach($retPend['body'] as $detail) {
                        if($detail->Status->Code != -102) { // -102 is expired, means we need to resend the image through post
                            $notExpired[] = $detail;
                            $unsetPath = $body["pendingURLs"][$detail->OriginalURL];
                            if(($key = array_search($unsetPath, $body["files"])) !== false) {
                                unset($body["files"][$key]);
                            }
                        }
                    }
                    $retPend['body'] = $notExpired;
                }
            }
        }
        if (isset($body["files"]) && count($body["files"]) ||
            isset($body["buffers"]) && count($body["buffers"])) {
            unset($body["pendingURLs"]);
            $retFiles = $this->requestInternal($method, $body, $header);
        }

        if(!isset($retUrls["body"]->Status) && !isset($retPend["body"]->Status) && !isset($retFiles["body"]->Status)
           && (!is_array($retUrls["body"]) || !is_array($retPend["body"]) || !is_array($retFiles["body"]))) {
            throw new Exception("Request inconsistent status. Please contact support.");
        }

        $body = isset($retUrls["body"]->Status)
            ? $retUrls["body"]
            : (isset($retPend["body"]->Status)
                ? $retPend["body"]
                : (isset($retFiles["body"]->Status)
                    ? $retFiles["body"] :
                    array_merge($retUrls["body"], $retPend["body"], $retFiles["body"])));

        $theReturn =  (object) array("body"    => $body,
                     "headers" => array_unique(array_merge($retUrls["headers"], $retPend["headers"], $retFiles["headers"])),
                     "fileMappings" => array_merge($retUrls["fileMappings"], $retPend["fileMappings"], $retFiles["fileMappings"]));
        ShortPixel::log("REQUEST RETURNS: " . json_encode($theReturn));
        return $theReturn;
    }
11375
public function setPostBody ($body)
    {
        if ($this->_sent) {
            throw new CAS_OutOfSequenceException(
                'Request has already been sent cannot '.__METHOD__
            );
        }
        if (!$this->isPost) {
            throw new CAS_OutOfSequenceException(
                'Cannot add a POST body to a GET request, use makePost() first.'
            );
        }

        $this->postBody = $body;
    }