逻辑处理.

@param string $url
@param array  $arg
@param bool   $charSetUTF8
@param bool   $retry
@param bool   $post

@return array

@throws TencentAIException
183173
public static function exec(string $url,
                                array $arg,
                                bool $charSetUTF8 = true,
                                bool $retry = false,
                                bool $post = true)
    {
        $retry_settings = 0;

        if (!$retry) {
            $retry_settings = self::$retry;
        }

        if (PHP_OS === 'WINNT') {
            self::$curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
        }
        $app_id = self::$app_id;
        $format = strtolower(self::$format);

        // @since 7.1
        $nonce_str = session_create_id();
        $data = [
            'app_id' => $app_id,
            'time_stamp' => time(),
            'nonce_str' => $nonce_str,
        ];
        $array = array_merge($data, $arg);
        ksort($array);
        $request_body = http_build_query($array);

        // 签名
        $sign = self::sign($request_body);

        // 最终请求体
        $data = $request_body."&sign=$sign";

        $request_url = 'https://api.ai.qq.com/fcgi-bin/'.$url;

        // 发起请求
        $method = $post ? 'post' : 'get';

        try {
            $json = self::$curl->$method($request_url, $data);

            if ($charSetUTF8) {
                $array = json_decode($json, true);
            } else {
                $json = mb_convert_encoding($json, 'utf8', 'gbk');
                $array = json_decode($json, true);
            }

            // 检查是否返回数组
            if (!\is_array($array)) {
                self::returnStr($json);
            }

            // 检查返回值
            self::checkReturn($array['ret']);
        } catch (\Throwable $e) {
            if (false === $retry) {
                for ($i = $retry_settings; $i > 0; --$i) {
                    self::$debug &&
                    file_put_contents(
                        sys_get_temp_dir().'/tencent_ai.log',
                        json_encode([
                            'url' => $url,
                            'retry' => $i,
                            'request_url' => $request_url,
                            'message' => $e->getMessage(),
                            'code' => $e->getCode(),
                        ], JSON_UNESCAPED_UNICODE)."\n", FILE_APPEND
                    );

                    try {
                        $result = self::exec($url, $arg, $charSetUTF8, true);

                        return $result;
                    } catch (TencentAIException $e) {
                        if (1 === $i) {
                            throw new TencentAIException($e->getCode(), $e->getMessage());
                        }

                        continue;
                    }
                }

                throw new TencentAIException($e->getCode(), $e->getMessage());
            } else {
                throw new TencentAIException($e->getCode(), $e->getMessage());
            }
        }

        if ('json' === $format) {
            return json_encode($array, JSON_UNESCAPED_UNICODE);
        } else {
            return $array;
        }
    }
374391
private function exec($url, $method = 'GET', $post_data = '')
    {

        if (!$url) {
            throw new \RuntimeException('CURL url is null:' . __FILE__);
        }
        $this->ch = curl_init();
        $this->defaultOptions($this->ch, $url);
        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $method);
        $is_file    = false;
        $encode_arr = [];
        $user_agent_params = [];
        if ($post_data) {
            if (is_array($post_data)) {
                // edit by jinxing.liu@verystar.cn 统一 user_agent 信息 start:
                if (isset($post_data['http_user_agent_params'])) {
                    $user_agent_params = (array)$post_data['http_user_agent_params'];
                    unset($post_data['http_user_agent_params']);
                }
                // end;

                foreach ($post_data as $k => $v) {
                    if ("@" != substr($v, 0, 1)) //判断是不是文件上传
                    {
                        $encode_arr[$k] = $v;
                    } else //文件上传用multipart/form-data，否则用www-form-urlencoded
                    {
                        $is_file        = true;
                        $encode_arr[$k] = new \CURLFile(substr($v, 1));
                    }
                }
            }

            if ($is_file) {
                curl_setopt($this->ch, CURLOPT_POSTFIELDS, $encode_arr);
            } else {
                $post_data = is_array($post_data) ? http_build_query($post_data) : $post_data;
                curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post_data);
            }
        }

        // edit by jinxing.liu@verystar.cn 统一 user_agent 信息 start:
        if (strpos($url, '.verystar.cn')) {
            array_unshift($user_agent_params, 'php');
            // 用户访问代理 User-Agent
            curl_setopt($this->ch, CURLOPT_USERAGENT, 'VeryPay/1.0 (' . implode('; ', $user_agent_params) . ')');
        }
        // end

        if ($this->http_header) {
//            $this->http_header = array(
//                'Content-Length: ' . strlen($post_data),
//                'Content-Type: ' . $content_type,
//                'Accept: ' . $accept_type
//            );
            curl_setopt($this->ch, CURLOPT_HTTPHEADER, $this->http_header);
        }
        $this->body       = curl_exec($this->ch);
        $this->curl_error = curl_errno($this->ch);
        $this->header     = curl_getinfo($this->ch);
        $this->log($url);
        if (is_resource($this->ch)) {
            curl_close($this->ch);
        }

        $this->url       = $url;
        $this->method    = $method;
        $this->post_data = $post_data;
        return $this;

    }
884295
public static function socketPost($url, $post_data = [], $timeout = 5, $header = "", $data_type = "")
    {
        $header = empty($header) ? self::defaultHeader() : $header;
        //支持json数据数据提交
        if ($data_type == 'json') {
            $post_string = json_encode($post_data);
        } else if (is_array($post_data)) {
            $post_string = http_build_query($post_data, '', '&');
        } else {
            $post_string = $post_data;
        }

        $url2 = parse_url($url);
        $url2["path"] = ($url2["path"] == "" ? "/" : $url2["path"]);
        $url2["port"] = ($url2["port"] == "" ? 80 : $url2["port"]);
        $host_ip = @gethostbyname($url2["host"]);
        $fsock_timeout = $timeout; //超时时间
        if (($fsock = fsockopen($host_ip, $url2['port'], $errno, $errstr, $fsock_timeout)) < 0) {
            return false;
        }
        $request = $url2["path"] . ($url2["query"] ? "?" . $url2["query"] : "");
        $in = "POST " . $request . " HTTP/1.0\r\n";
        $in .= "Host: " . $url2["host"] . "\r\n";
        $in .= $header;
        $in .= "Content-type: application/x-www-form-urlencoded\r\n";
        $in .= "Content-Length: " . strlen($post_string) . "\r\n";
        $in .= "Connection: Close\r\n\r\n";
        $in .= $post_string . "\r\n\r\n";
        unset($post_string);
        if (!@fwrite($fsock, $in, strlen($in))) {
            @fclose($fsock);
            return false;
        }
        return self::GetHttpContent($fsock);
    }
1236039
protected ParsedResume parseResume(String url, Object requestPayLoad, Map<String, String> uriVariables) {
        ParsedResume response = null;
        for (int tryNumber = 1; tryNumber <= RESUME_PARSE_RETRY; tryNumber++) {
            try {
                response = this.performPostResumeRequest(url, requestPayLoad, uriVariables);
                break;
            } catch (HttpStatusCodeException error) {
                response = handleResumeParseError(tryNumber, error);
            } catch (Exception e) {
                log.error("error", e);
            }
        }

        return response;
    }
920163
public function execute($url, $params = [])
    {
        $uri = rtrim(rtrim($this->site, '/') . '/' . ltrim($url, '/') . '?' . http_build_query($params), '?');

        try {
            $result = $this->client->get($uri, ['timeout' => 10])->getBody();

            return ($this->format === 'json') ? json_decode($result) : (string) $result;
        } catch (\Exception $e) {
            if ($this->isRetry) {
                $msg = "Error connecting to the Extension Marketplace:\n" . $e->getMessage();
                throw new SatisQueryException($msg, $e->getCode(), $e);
            }
            $this->isRetry = true;
            $this->site = str_replace('https://', 'http://', $this->site);

            return $this->execute($url, $params);
        }
    }
16681
public static function error($args) {
        if (is_string($args) || is_numeric($args)) {
            return [0, '成功', $args, ''];
        }
        if (is_array($args) && isset($args['__def'])) {
            unset($args['__def']);
            return [0, '成功', $args, ''];
        }
        #根据不同的参数个数进行判断
        switch (count($args)) {
        case 0:
            return [0, '成功', [], ''];
            break;
        case 1:
            $arg1 = reset($args);
            #如果是数字
            if (is_numeric($arg1)) {
                if ($arg1 === 0) {
                    return [0, '成功', [], ''];
                } else {
                    return [$arg1, '错误', [], ''];
                }
            }
            #如果是字符串
            if (is_string($arg1)) {
                return [0, $arg1, [], ''];
            }
            #如果是数组
            if (is_array($arg1)) {
                if (empty($arg1)) {
                    return [-2, '数据为空', [], ''];
                } else {
                    return [0, '成功', $arg1, ''];
                }
            }
            break;
        case 2:
            $arg1 = reset($args);
            $arg2 = next($args);
            if (is_numeric($arg1) && is_string($arg2)) {
                return [$arg1, $arg2, [], ''];
            }
            if (is_string($arg1) && is_array($arg2)) {
                if (empty($arg2)) {
                    return [-2, $arg1, [], ''];
                } else {
                    return [0, '成功', $arg2, ''];
                }
            }
            if (is_array($arg1) && is_array($arg2)) {
                #如果数组为空
                if (empty($arg2) && empty($arg1)) {
                    return [-2, '失败', [], ''];
                }
                #如果第二个参数为空
                elseif (empty($arg2)) {
                    return [-2, reset($arg1), [], ''];
                } else {
                    $arg1 = next($arg1);
                    $arg1 = empty($arg1) ? '成功' : $arg1;
                    return [0, $arg1, $arg2, ''];
                }
            }
            break;
        case 3:
            $arg1 = reset($args);
            $arg2 = next($args);
            $arg3 = next($args);
            if (is_object($arg1) && is_string($arg2) && is_array($arg3)) {
                return [$arg1, $arg2, $arg3, ''];
            }
            if (is_numeric($arg1) && is_string($arg2) && is_array($arg3)) {
                return [$arg1, $arg2, $arg3, ''];
            }
            if (is_numeric($arg1) && is_string($arg2) && is_numeric($arg3)) {
                return [$arg1, $arg2, $arg3, ''];
            }
            if (is_numeric($arg1) && is_string($arg2) && is_string($arg3)) {
                $arg3 = static::params($arg3) ? static::params($arg3) : $arg3;
                return [$arg1, $arg2, [], $arg3];
            }
            if (is_array($arg1) && is_array($arg2) && is_string($arg3)) {
                #如果数组为空
                if (empty($arg2) && empty($arg1)) {
                    return [-2, '失败', [], ''];
                }
                #如果第二个参数为空
                elseif (empty($arg2)) {
                    return [-2, reset($arg1), [], ''];
                } else {
                    $arg1 = next($arg1);
                    $arg1 = empty($arg1) ? '成功' : $arg1;
                    $arg3 = static::params($arg3) ? static::params($arg3) : $arg3;
                    return [0, $arg1, $arg2, $arg3];
                }
            }
            break;
        case 4:
        default:
            $arg1 = reset($args);
            $arg2 = next($args);
            $arg3 = next($args);
            $arg4 = next($args);
            if (is_numeric($arg1) && is_string($arg2) && is_array($arg3) && is_string($arg4)) {
                $arg4 = static::params($arg4) ? static::params($arg4) : $arg4;
                return [$arg1, $arg2, $arg3, $arg4];
            }
            break;
        }
        return [0, '其他', $args, ''];
    }
342869
public static String post(
      String serverUrl, String realData, int connectTimeout, int readTimeout, String charset)
      throws NoSuchAlgorithmException, KeyManagementException, IOException {
    if (serverUrl == null || "".equals(serverUrl.trim())) {
      throw new NullPointerException("请求地址为空!");
    }
    if (realData == null || "".equals(realData.trim())) {
      throw new NullPointerException("请求数据为空!");
    }
    URLConnection conn;
    // 分别调用http或https请求
    if (serverUrl.startsWith(HTTPS_PREFIX)) {
      SSLContext sslContext = SSLContext.getInstance("TLS");
      X509TrustManager[] xtmArray = new X509TrustManager[] {xtm};
      sslContext.init(null, xtmArray, new java.security.SecureRandom());
      HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
      HttpsURLConnection.setDefaultHostnameVerifier(hnv);
      HttpsURLConnection httpsUrlConn = (HttpsURLConnection) (new URL(serverUrl)).openConnection();
      httpsUrlConn.setRequestMethod("POST");
      conn = httpsUrlConn;
    } else {
      URL url = new URL(serverUrl);
      conn = url.openConnection();
    }
    conn.setConnectTimeout(connectTimeout * 1000);
    conn.setReadTimeout(readTimeout * 1000);
    conn.setRequestProperty("Content-Type", "application/json;charset=" + charset);

    conn.setDoOutput(true);
    conn.setDoInput(true);

    OutputStream out = conn.getOutputStream();
    try {
      out.write(realData.getBytes(charset));
      out.flush();
    } finally {
      out.close();
    }

    InputStream is = conn.getInputStream();
    // 返回收到的响应数据
    return getResponseStringData(is, charset);
  }
1111879
public static String doPost(String url, Map<String, String> params, String charset, int connectTimeout, int readTimeout) throws IOException {
        return doPost(url, params, charset, connectTimeout, readTimeout, null);
    }
812382
public String getValueFromServer(String url) throws Exception {

        // 远程地址
        RemoteUrl remoteUrl = new RemoteUrl(url, hostList);

        ValueVo confItemVo = restfulMgr.getJsonData(ValueVo.class, remoteUrl, retryTime, retrySleepSeconds);
        LOGGER.debug("remote server return: " + confItemVo.toString());

        if (confItemVo.getStatus().equals(Constants.NOTOK)) {
            throw new Exception("status is not ok.");
        }

        return confItemVo.getValue();
    }
2499
public function log_http_response( $response, array $args, $url ) {
		$this->data['http'][ $args['_qm_key'] ]['end']      = microtime( true );
		$this->data['http'][ $args['_qm_key'] ]['response'] = $response;
		$this->data['http'][ $args['_qm_key'] ]['args']     = $args;
		if ( isset( $args['_qm_original_key'] ) ) {
			$this->data['http'][ $args['_qm_original_key'] ]['end']      = $this->data['http'][ $args['_qm_original_key'] ]['start'];
			$this->data['http'][ $args['_qm_original_key'] ]['response'] = new WP_Error( 'http_request_not_executed', sprintf(
				/* translators: %s: Hook name */
				__( 'Request not executed due to a filter on %s', 'query-monitor' ),
				'pre_http_request'
			) );
		}

		$this->data['http'][ $args['_qm_key'] ]['info']      = $this->info;
		$this->data['http'][ $args['_qm_key'] ]['transport'] = $this->transport;
		$this->info      = null;
		$this->transport = null;
	}
542540
function build($url,$args=[]) {
		$args+=$this->hive['PARAMS'];
		if (is_array($url))
			foreach ($url as &$var) {
				$var=$this->build($var,$args);
				unset($var);
			}
		else {
			$i=0;
			$url=preg_replace_callback('/@(\w+)|(\*)/',
				function($match) use(&$i,$args) {
					if (isset($match[1]) &&
						array_key_exists($match[1],$args))
						return $args[$match[1]];
					if (isset($match[2]) &&
						array_key_exists($match[2],$args)) {
						if (!is_array($args[$match[2]]))
							return $args[$match[2]];
						$i++;
						return $args[$match[2]][$i-1];
					}
					return $match[0];
				},$url);
		}
		return $url;
	}
361675
public function queryOrder(array $args = array()) {
        $args = $this->getQuery()->parameters($this->merge($args))->json();
        if (!array_key_exists('alipay_trade_query_response', $args)) {
            throw new \Exception('未知错误！');
        }
        $args = $args['alipay_trade_query_response'];
        if ($args['code'] != 10000) {
            throw new \Exception($args['msg']);
        }
        if (!$this->verify($args)) {
            throw new \Exception('数据验签失败！');
        }
        return $args;
    }
1167147
public function append($url = '', $argsOrParams = array(), $params = array())
    {
        if (strpos($url, '%s') !== false) {
            $url = vsprintf($url, (array)$argsOrParams);
        } else {
            $params = $argsOrParams;
        }
        if ($params) {
            $url .= (false === strpos($url, '?') ? '?' : '&');
        }
        return $url . (is_array($params) ? http_build_query($params) : $params);
    }
762729
function post($url, $parameters = array(), $multi = false) {
    $response = $this->oAuthRequest($url, 'POST', $parameters, $multi );
    if ($this->format === 'json' && $this->decode_json) {
      return json_decode($response, true);
    }
    return $response;
  }
432026
private function nlp($url, $text, bool $charSetGBK = true)
    {
        if ($charSetGBK) {
            $data = [
                'text' => mb_convert_encoding($text, 'gbk', 'utf8'),
            ];

            return Request::exec($url, $data, false);
        }

        $data = [
            'text' => $text,
        ];

        return Request::exec($url, $data);
    }
1144623
public function query($url = '', $argsOrParams = array(), $params = array())
    {
        if (strpos($url, '%s') === false) {
            $argsOrParams = $argsOrParams + $this->request->getQueries();
        } else {
            $params += $this->request->getQueries();
        }
        return $this->__invoke($url, $argsOrParams, $params);
    }
28957
public function goPost($url = '', $data = [], $timeout = 30000, $headers = [])
    {
        if (empty($data)) {
            throw new Exception('post data is empty');
        }

        if (!($this->client instanceof \swoole_http_client)) {
            throw new Exception('You must complete the DNS query first, Such as $client->goDnsLookup()');
        }

        if (empty($this->urlData)) {
            $this->urlData = self::parseUrl($url);
        } else {
            if (!empty($url)) {
                $this->urlData['path'] = $url;
            }
        }
        $this->setHeaders($headers);
        $sendPostReq  = $this->getObject(Http::class, [$this, 'POST', $this->urlData['path'], $data, $timeout]);

        return $sendPostReq;
    }