php socket 发送HTTP请求 POST json

* HttpRequest.php

<?php
namespace et\http;

/**
 * Created by PhpStorm.
 * User: mingzhanghui
 * Date: 2018-09-18
 * Time: 16:19
 */
class HttpRequest {
    const BUFSIZE = 4096;
    const DEFAULT_OPTIONS = [
        'port' => 80,
        'timeout'=> 30
    ];

    const DEFAULT_HEADRES = [
        'Content-Type' => 'application/x-www-form-urlencoded'
    ];

    public static function mergeDefaultOptions(Array& $to, Array $default) {
        foreach ($default as $key => $value) {
            if (!array_key_exists($key, $to)) {
                $to[$key] = $value;
            }
        }
    }

    /**
     * @param $host string remote server '192.168.1.219:7102' without http://
     * @param $uri string remote uri '/service/pageinfo/'
     * @param $headers
     * @param string $body
     * @param array $options
     * @return string
     * @throws \Exception
     */
    public static function post($host, $uri, $headers = [], $body = "", $options = []) {
        self::mergeDefaultOptions($options, self::DEFAULT_OPTIONS);

        $socket = fsockopen($host, $options['port'], $errno, $errstr, $options['timeout']);
        if (!$socket) {
            throw new \Exception(sprintf("%s(%d)", $errstr, $errno));
        }

        fwrite($socket, sprintf("POST %s HTTP/1.0\r\n", $uri));
        fwrite($socket, "User-Agent: Socket_Backstage\r\n");
        fwrite($socket, sprintf("Content-length: %d\r\n", strlen($body)));
        fwrite($socket, "Accept: */*\r\n");

        self::mergeDefaultOptions($headers, self::DEFAULT_HEADRES);
        foreach ($headers as $name => $value) {
            fwrite($socket, $name.": ".$value."\r\n");
        }
        fwrite($socket, "\r\n");

        fwrite($socket, $body."\r\n");
        fwrite($socket, "\r\n");

        $header = "";
        while ($str = trim(fgets($socket, self::BUFSIZE))) {
            $header .= $str;
        }
        $resp = "";
        while (!feof($socket)) {
            $resp .= fgets($socket, self::BUFSIZE);
        }
        return $resp;
    }

    public static function get($host, $uri, $data, $port=80, $timeout = 30) {
        $socket = fsockopen($host, $port, $errno, $errstr, $timeout);
        if (!$socket) {
            throw new \Exception(sprintf("%s(%d)", $errstr, $errno));
        }
        $qs = http_build_query($data, '', '&');

        fwrite($socket, sprintf("GET %s?%s HTTP/1.0\r\n", $uri, $qs));
        fwrite($socket, "User-Agent: Socket_Backstage\r\n");
        fwrite($socket, "Content-type: application/x-www-form-urlencoded\r\n");
        fwrite($socket, sprintf("Content-length: %d\r\n", strlen($qs)));
        fwrite($socket, "Accept: */*\r\n");
        fwrite($socket, "\r\n");
        fwrite($socket, "\r\n");

        $header = "";
        while ($str = trim(fgets($socket, self::BUFSIZE))) {
            $header .= $str;
        }
        $resp = "";
        while (!feof($socket)) {
            $resp .= fgets($socket, self::BUFSIZE);
        }
        return $resp;
    }

    /**
     * $.post(url, data, function(data) { ... })
     * @param $url
     * @param $data
     * @return mixed
     * @throws \Exception
     */
    public static function post_url($url, Array $data) {
        $components = parse_url($url);
        if ($components === false) {
            throw new \Exception('url is not valid');
        }
        if ($components['scheme'] != 'http') {
            throw new \Exception('scheme is not http');
        }
        $host = $components['host'];
        $path = empty($components['path']) ? '/' : $components['path'];

        $headers = [
            'Content-Type' => 'application/x-www-form-urlencoded'
        ];
        $body = http_build_query($data, '', '&');

        return self::post($host, $path, $headers, $body, self::DEFAULT_OPTIONS);
    }
}

* test

index.php

<?php
/**
 * Created by PhpStorm.
 * User: mingzhanghui
 * Date: 2018-09-18
 * Time: 10:46
 */
include 'HttpRequest.php';

// $response = \et\http\HttpRequest::get('www.baidu.com', '/', []);
// $body = http_build_query($data, '', '&');

$headers = ['Content-Type' => 'application/json'];
// $body = "{\"query\":{\"bool\":{\"must\":[{\"match_phrase_prefix\":{\"request\":\"/cgi-bin/service\"}},{\"range\":{\"@timestamp\":{\"gte\":\"2017-09-11 09:26:10\",\"lte\":\"2018-09-13 09:27:10\",\"format\":\"yyyy-MM-dd HH:mm:ss\"}}},{\"range\":{\"request_time\":{\"gte\":5}}}]}},\"sort\":[{\"request_time\":{\"order\":\"desc\"}}],\"size\":10}";

function buildQueryBodySlow($uri, $begin, $end, $requestTime = 5, $size = 10) {
    $o = new \stdClass();
    $o->query = new \stdClass();
    $o->query->bool = new \stdClass();
    $o->query->bool->must = [
        0 => ['match_phrase_prefix' => [
            'request' => $uri
        ]],
        1 => ['range' => [
            '@timestamp' => [
                "gte"=> $begin,
                "lte"=> $end,
                "format"=> "yyyy-MM-dd HH:mm:ss"
            ]
        ]],
        2 => ['range' => [
            'request_time' => ['gte' => $requestTime]
        ]]
    ];
    $o->sort = [
        0 => [
            'request_time'=> [
                'order'=>'desc'
            ]
        ]
    ];
    $o->size = $size;

    return json_encode($o);
}

$body = buildQueryBodySlow(
    '/cgi-bin/service',
    "2017-09-11 09:26:10",
    "2018-09-13 09:27:10",
    5,
    1
);

// post json
$response = et\http\HttpRequest::post(
    '172.16.0.245',
    '/filebeat-2018.09.12/_search?pretty',
    $headers,
    $body,
    ['port'=>9200]
);

echo '<pre>';
print_r($response);

猜你喜欢

转载自blog.csdn.net/fareast_mzh/article/details/82761623